﻿Imports System.Data.Sql
Imports System.Data.SqlClient
Imports System.Xml


Public Class Frm_INToutofstrorage

    Implements IDServer.IDServer.IDServer


    Public ActionHelp As IDServer.IDServer.ActionBtn = IDServer.IDServer.ActionBtn.ActionHelp

    Private ElementDS As DataSet
    Private MasterDS As DataSet
    Private DetailDS As DataSet
    Private dselement As DataSet
    Private GoodsDS As DataSet
    Private StoreDS As DataSet
    Private StorePlaceDS As DataSet
    Private strsql As String
    Private mShopCode As String
    Private PeriodData As String
    Private IsPlace As Boolean
    Private IsPlace1 As Boolean
    Private IsClose As Boolean
    Private Fields As String
    Private bFind As Boolean
    Private IsImport As Boolean = False
    Dim B As Boolean
    Private WithEvents MainForm As Frm_MainForm
    Private currentBatch As String
    Private currentStoreplace As String
    Private currentBarcode As String
    Private ReadQTY As Integer
    Private dt As DataTable


    Public Property SelectObject() As Frm_MainForm
        Get
            Return MainForm
        End Get
        Set(ByVal value As Frm_MainForm)
            MainForm = value
        End Set
    End Property

    Public Property ShopCode() As String
        Get
            Return mShopCode

        End Get
        Set(ByVal value As String)
            mShopCode = value
        End Set
    End Property



#Region "define event"

    Private Sub Frm_INTInStorage_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Try
            Me.Panel6.Visible = True
            BindDataGridViewMaster()
            BindDataGridViewDetail()
            BindElementGridView()
            SetGridCaptionVisible(Me.DGV_Master, Fields, "Frm_INToutofstrorage")
            IsAmountClose()
            LoadStoreType()
            LoadPopfrmInfo()
            LoadGoods()
            SetEnable(False)
            btnelement.Visible = False
            Me.cmbToStore1.Enabled = False
            Me.LabOperatePerson.Text = PubUserName
            Me.LabOperateDate.Text = ServerDate
            Me.TabPage1.Focus()
        Catch ex As Exception
            MessageBox.Show(ex.ToString + ex.Message, "error", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End Try

    End Sub

    Private Sub txtbarcode_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
        If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
            viewgood()
        End If


    End Sub

    Private Sub checkbarcode()

        Try
            'If Me.txtbarcode.Text.Length <= 0 Then Exit Sub
            'Dim StoreHouse As String
            'Dim status As String
            'If Me.cmbFromStore1.Text.Length > 0 Then
            '    StoreHouse = Me.cmbFromStore1.SelectedItem.ToString.Split(Space(5))(0)
            'Else
            '    StoreHouse = ""
            'End If
            ''If Me.cmboutstatus.Text.Length > 0 Then
            ''    status = Me.cmboutstatus.SelectedItem.ToString.Split(Space(5))(0)
            ''Else
            ''    status = ""
            ''End If

            'strsql = "select * from BSC_goods where Barcode='*" + txtbarcode.Text.Trim + "*'; "
            'strsql += "select *  from  Stor_elment  where goodsBarcode='*" + txtbarcode.Text.Trim + "*' and tostore='" + StoreHouse + "' and  elementstatus='" + Microsoft.VisualBasic.Left(cmbstatus.Text, cmbstatus.Text.IndexOf(" ")) + "'  order by element "
            'dsbarcode = ReturnDataset(strsql)
            'If dsbarcode.Tables(0).Rows.Count < 1 Then
            '    txtbarcode.Text = ""
            '    txtbarcode.Focus()
            'Else
            '    viewgood()
            '    txtbarcode.SelectAll()
            'End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Exclamation Or MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub viewgood()

        Try
            'If Me.txtbarcode.Text.Length <= 0 Then Exit Sub
            'Dim StoreHouse As String
            'Dim status As String
            'If Me.cmbFromStore1.Text.Length > 0 Then
            '    StoreHouse = Me.cmbFromStore1.SelectedItem.ToString.Split(Space(5))(0)
            'Else
            '    StoreHouse = ""
            'End If
            'If Me.cmboutstatus.Text.Length > 0 Then
            '    status = Me.cmboutstatus.SelectedItem.ToString.Split(Space(5))(0)
            'Else
            '    status = ""
            'End If

            'strsql = "select * from BSC_goods where Barcode='*" + txtbarcode.Text.Trim + "*' ;"
            'strsql += "select a.*,b.tostore  from  Stor_element a, stor_trademaster b  where a.elementIsOut=0 and goodsBarcode='*" + txtbarcode.Text.Trim + "*' and   a.elementstatus ='" + status + "' and  a.storeplace='" + txtplace.Text + "' and a.elementbatch='" + Cmbgoodsbatch.Text + "'and  a.bonuma=b.bonum order by element;"
            'strsql += "select a.tostore,a.operatedate,b.goodsbarcode,b.batch  from stor_trademaster a, stor_tradedetail b ,Bsc_storehouse c  where a.bonum=b.bonum and a.tostore=c.fcode and c.fshortname='" + cmbFromStore1.Text + "' and b.goodsBarcode='*" + txtbarcode.Text.Trim + "*'  order by operatedate asc; "
            'strsql += "select * from stor_storagehistory where barcode='*" + txtbarcode.Text.Trim + "*'"
            'dsbarcode = New DataSet
            'dsbarcode = ReturnDataset(strsql)

            'If dsbarcode.Tables(0).Rows.Count <= 0 Then
            '    txtbarcode.Text = ""
            '    txtbarcode.Focus()
            'End If
            'For Each drow As DataRow In dsbarcode.Tables(0).Rows
            '    txtcode.Text = drow("code")
            '    txtcolor.Text = drow("color")
            '    txtsize.Text = drow("spec")
            '    txtunit.Text = drow("unit")
            '    B = drow("Iselement")
            '    btnelement.Visible = B
            '    lstviewelement.Visible = B
            'Next
            'If lstviewelement.Visible = True Then
            '    If dsbarcode.Tables(1).Rows.Count > 0 Then
            '        For Each drowelement As DataRow In dsbarcode.Tables(1).Rows
            '            Dim item As New ListViewItem
            '            item.Text = drowelement("element")
            '            Me.lstviewelement.Items.Add(item)
            '            item.SubItems.Add(drowelement("elementamount"))
            '            item.SubItems.Add(drowelement("elementunit"))
            '            item.SubItems.Add(drowelement("elementbatch"))
            '            item.SubItems.Add(drowelement("storeplace"))
            '            item.SubItems.Add(drowelement("elementstatus"))
            '        Next
            '    End If
            'End If
            'Cmbgoodsbatch.Items.Clear()
            'If dsbarcode.Tables(2).Rows.Count >= 1 Then
            '    For Each batch As DataRow In dsbarcode.Tables(2).Rows
            '        Cmbgoodsbatch.Items.Add(batch("batch"))
            '    Next
            'End If
            'If dsbarcode.Tables(3).Rows.Count >= 1 Then
            '    For Each batch As DataRow In dsbarcode.Tables(3).Rows
            '        Cmbgoodsbatch.Items.Add(batch("batch"))
            '    Next
            'End If
        Catch ex As Exception
            MsgBox("viewgood:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Function checktradecode(ByVal tt As ComboBox) As Boolean

        Try
            Dim ttt As String
            Dim tradecode As New DataSet
            Dim strsql As String = ""
            strsql = "select * from stor_tradecode where code='" + tt.Text.Substring(0, 2) + "'"
            tradecode = ReturnDataset(strsql)
            If tradecode.Tables(0).Rows.Count < 1 Then
                checktradecode = False
            Else
                For Each drow As DataRow In tradecode.Tables(0).Rows
                    ttt = drow("addornot")
                Next
                If ttt.Trim = "T" Then
                    Return True
                Else
                    Return False
                End If
            End If

        Catch ex As Exception
            MessageBox.Show(ex.ToString, "error", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End Try

    End Function

    Private Sub btnelement_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    End Sub


    Private Function ReturnTable(ByVal BoNum As String, Optional ByVal index As Integer = 0) As DataTable
        Try
            Dim mTable As New DataTable

            Select Case index
                Case 0

                    With mTable
                        .Columns.Add("BoNum")
                        .Columns.Add("ItemNo")
                        .Columns.Add("PoNum")
                        .Columns.Add("PoNumItem")
                        .Columns.Add("DeliverNo")
                        .Columns.Add("GoodsBarCode")
                        .Columns.Add("Batch")
                        .Columns.Add("GoodsStatus")
                        .Columns.Add("StorePlace")
                        .Columns.Add("Goodsamount")
                        .Columns.Add("goodsother")
                    End With


                    For Each Row As DataRow In DetailDS.Tables(0).Rows
                        Dim mRow As DataRow = mTable.NewRow
                        mRow("BoNum") = BoNum
                        mRow("ItemNo") = Row("ItemNo") & ""
                        mRow("PoNum") = Row("PoNum") & ""
                        mRow("PoNumItem") = ""
                        mRow("DeliverNo") = Me.txtSaleOrdeNo.Text
                        mRow("GoodsBarCode") = "*" & Row("GoodsBarCode") & "*"
                        mRow("Batch") = Row("Batch") & ""
                        mRow("GoodsStatus") = 1
                        mRow("StorePlace") = Row("StorePlace") & ""
                        mRow("Goodsamount") = Row("Goodsamount") & ""
                        mRow("goodsother") = Row("goodsother") & ""
                        mTable.Rows.Add(mRow)
                    Next
                    mTable.AcceptChanges()
                    Return mTable
                Case 1

                    With mTable
                        .Columns.Add("BoNumB")
                        .Columns.Add("GoodsBarcode")
                        .Columns.Add("Element")
                        .Columns.Add("Elementamount")
                        .Columns.Add("ElementBatch")
                        .Columns.Add("ElementPlace")
                        .Columns.Add("ElementStatus")
                        .Columns.Add("ElementUnit")
                        .Columns.Add("ElementComputer")
                    End With

                    For i As Integer = 0 To Me.lstviewelement.CheckedItems.Count - 1
                        Dim mRow As DataRow = mTable.NewRow

                        mRow("BoNumB") = BoNum
                        mRow("GoodsBarcode") = "*" & txtEleBarcode.Text & "*"
                        mRow("Element") = Me.lstviewelement.CheckedItems(i).SubItems(0).Text
                        mRow("Elementamount") = Me.lstviewelement.CheckedItems(i).SubItems(1).Text
                        mRow("ElementBatch") = Me.lstviewelement.CheckedItems(i).SubItems(3).Text
                        mRow("ElementPlace") = Me.lstviewelement.CheckedItems(i).SubItems(4).Text
                        mRow("ElementStatus") = Me.lstviewelement.CheckedItems(i).SubItems(5).Text
                        mRow("ElementUnit") = Me.lstviewelement.CheckedItems(i).SubItems(2).Text
                        mRow("ElementComputer") = My.Computer.Name
                        mTable.Rows.Add(mRow)
                    Next
                    mTable.AcceptChanges()
                    Return mTable
            End Select

        Catch ex As Exception
            Return Nothing
            MsgBox("ReturnTable:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Function

    Private Sub savetodatabase()

        If ActionInitialize() = False Then Exit Sub
        Dim sqlConn As New SqlConnection
        Dim sqlcmd As New SqlCommand
        Dim SqlBulk As SqlClient.SqlBulkCopy
        sqlConn = GetConn()

        If sqlConn.State = ConnectionState.Closed Then
            sqlConn.Open()
        End If
        Dim transqlserver As SqlTransaction = sqlConn.BeginTransaction
        Try

            Dim readtime As String = Now.Hour.ToString + ":" + Now.Minute.ToString + ":" + Now.Second.ToString
            Dim Mtradetype As String = ""
            Dim Minorouttype As String = ""
            Dim Mtostore As String = Me.cmbFromStore.SelectedValue
            Dim Mfromstore As String = ""
            Dim Mstoreplace As String = ""
            Dim Mdeliverno As String = ""
            Dim Mdeliverperson As String = ""
            Dim Mdeliverdate As String = ""
            Dim Mdelivercar As String = ""
            Dim mbatch As String = ""
            Dim Mopterationdate As String = ""
            Dim Mremarks As String = ""
            Dim readcomputername As String = My.Computer.Name
            Dim Mgoodsbarcode As String = ""
            Dim mgoodsstatus As String = ""
            Dim TradeType As String = Me.cmbStoreOperate.SelectedValue.ToString
            Dim InOrOutType As String = Me.cmbOutStoreType.SelectedValue.ToString
            Dim OperaterDate As String = ServerDate
            Dim ToStore As String = ""
            Dim FromStore As String = ""
            Dim BoStatus As String = Me.cmbBoStatus.SelectedValue.ToString
            Dim StorePlace As String = Me.txtStorePlace1.Text
            Dim DeliverNo As String = Me.txtSaleOrdeNo.Text
            Dim DeliverPerson As String = Me.txtDeliverPerson.Text
            Dim DeliverDate As String = Format(Me.DateTimePicker2.Value, "yyyy-MM-dd")
            Dim DeliverCar As String = Me.txtDeliverCar.Text
            Dim Batch As String = ""
            Dim Remark As String = Me.txtRemark.Text

            If Me.cmbToStore1.Enabled = True Then
                If Not Me.cmbToStore1.SelectedValue Is Nothing Then
                    ToStore = Me.cmbToStore1.SelectedValue.ToString
                Else
                    ToStore = ""
                End If
            Else
                ToStore = ""
            End If

            If Me.cmbFromStore.SelectedValue Is Nothing Then
                FromStore = ""
            Else
                FromStore = Me.cmbFromStore.SelectedValue.ToString
            End If
            Dim sqlstr As String = ""
            Dim InStoreNo As String = ""
            Dim sql As String
            Dim TradeCode As String = ""
            Dim BoNum As String = AutoCreateBoNum(PubCompanyCode, Me.cmbStoreOperate.SelectedValue, Me.cmbFromStore.SelectedValue, "Stor_TradeMaster")


            If Me.TabControl1.SelectedIndex = 1 Then
                If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Then

                    'If Me.cmbOutStoreType.SelectedIndex = 2 Then
                    '    sql = "Insert Into Stor_TradeMaster(BoNum,TradeType,InOrOuttype,ToStore,FromStore,StorePlace,DeliverNo,DeliverPerson,DeliverDate,DeliverCar,Batch,BoStatus,Remark,OperatePerson,OperateComputer) values('"
                    '    sql += BoNum & "','" & TradeType & "','" & InOrOutType & "','" & ToStore & "','" & FromStore & "','" & StorePlace & "','" & DeliverNo & "','" & DeliverPerson & "','" & DeliverDate & "','" & DeliverCar & "','"
                    '    sql += Batch & "','" & BoStatus & "','" & Remark & "','" & PubUserName & "','" & My.Computer.Name & "')"
                    '    With sqlcmd
                    '        .Connection = sqlConn
                    '        .Transaction = transqlserver
                    '        .CommandType = CommandType.Text
                    '        .CommandText = sql
                    '        .ExecuteNonQuery()
                    '    End With
                    '    Dim mTable As DataTable = ReturnTable(BoNum, 0)
                    '    SqlBulk = New SqlClient.SqlBulkCopy(sqlConn, SqlBulkCopyOptions.Default, transqlserver)
                    '    SqlBulk.DestinationTableName = "Stor_TradeDetail"
                    '    SqlBulk.BulkCopyTimeout = 100
                    '    SqlBulk.WriteToServer(mTable)

                    '    sql = "Insert Into Stor_TradeMaster(BoNum,TradeType,InOrOuttype,ToStore,FromStore,StorePlace,DeliverNo,DeliverPerson,DeliverDate,DeliverCar,Batch,BoStatus,Remark,OperatePerson,OperateComputer) values('"
                    '    sql += InStoreNo & "','+','04','" & ToStore & "','" & FromStore & "','" & StorePlace & "','" & DeliverNo & "','" & DeliverPerson & "','" & DeliverDate & "','" & DeliverCar & "','"
                    '    sql += Batch & "','" & BoStatus & "','" & Remark & "','" & PubUserName & "','" & My.Computer.Name & "')"
                    '    With sqlcmd
                    '        .Connection = sqlConn
                    '        .Transaction = transqlserver
                    '        .CommandType = CommandType.Text
                    '        .CommandText = sql
                    '        .ExecuteNonQuery()
                    '    End With
                    '    Dim nTable As DataTable = ReturnTable(InStoreNo, 0)
                    '    SqlBulk = New SqlClient.SqlBulkCopy(sqlConn, SqlBulkCopyOptions.Default, transqlserver)
                    '    SqlBulk.DestinationTableName = "Stor_TradeDetail"
                    '    SqlBulk.BulkCopyTimeout = 100
                    '    SqlBulk.WriteToServer(nTable)
                    'Else
                    'End If
                    sql = "Insert Into Stor_TradeMaster(BoNum,TradeType,InOrOuttype,ToStore,FromStore,StorePlace,DeliverNo,DeliverPerson,DeliverDate,DeliverCar,Batch,BoStatus,Remark,OperatePerson,OperateComputer) values('"
                    sql += BoNum & "','" & TradeType & "','" & InOrOutType & "','" & ToStore & "','" & FromStore & "','" & StorePlace & "','" & DeliverNo & "','" & DeliverPerson & "','" & DeliverDate & "','" & DeliverCar & "','"
                    sql += Batch & "','" & BoStatus & "','" & Remark & "','" & PubUserName & "','" & My.Computer.Name & "')"
                    With sqlcmd
                        .Connection = sqlConn
                        .Transaction = transqlserver
                        .CommandType = CommandType.Text
                        .CommandText = sql
                        .ExecuteNonQuery()
                    End With

                    Dim NewTable As DataTable = ReturnTable(BoNum, 0)
                    SqlBulk = New SqlClient.SqlBulkCopy(sqlConn, SqlBulkCopyOptions.Default, transqlserver)
                    SqlBulk.DestinationTableName = "Stor_TradeDetail"
                    SqlBulk.BulkCopyTimeout = 100

                    Try
                        SqlBulk.WriteToServer(NewTable)
                    Catch ex As Exception
                        transqlserver.Rollback()
                        Exit Sub
                    Finally
                        NewTable = Nothing
                    End Try

                    Me.LabInfo.Text = BoNum
                    AddtoDataset(BoNum, Me.cmbStoreOperate.Text, Me.cmbOutStoreType.Text, Me.cmbToStore1.Text, Me.cmbFromStore.Text, OperaterDate, StorePlace, DeliverNo, DeliverPerson, DeliverDate, DeliverCar, Batch, Me.cmbBoStatus.Text, Remark, PubUserName)
                ElseIf ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
                    sql = "Update Stor_TradeMaster Set InOrOutType='" & InOrOutType & "',ToStore='" & ToStore & "',FromStore='" & FromStore & "',StorePlace='" & StorePlace & "',DeliverNo='" & DeliverNo
                    sql += "',DeliverPerson='" & DeliverPerson & "',DeliverDate='" & DeliverDate & "',DeliverCar='" & DeliverCar & "',Batch='" & Batch & "',Remark='" & Remark & "',UpdatePerson='" & PubUserName
                    sql += "',UpdateDate=getdate(),UpdateComputer='" & My.Computer.Name & "' where BoNum='" & Me.LabInfo.Text & "';"
                    sql += "Delete Stor_TradeDetail where BoNum='" & Me.LabInfo.Text & "'"
                    With sqlcmd
                        .Connection = sqlConn
                        .Transaction = transqlserver
                        .CommandType = CommandType.Text
                        .CommandText = sql
                        .ExecuteNonQuery()
                    End With

                    Dim NewTable As DataTable = ReturnTable(Me.LabInfo.Text, 0)
                    SqlBulk = New SqlClient.SqlBulkCopy(sqlConn, SqlBulkCopyOptions.Default, transqlserver)
                    SqlBulk.DestinationTableName = "Stor_TradeDetail"
                    SqlBulk.BulkCopyTimeout = 100

                    Try
                        SqlBulk.WriteToServer(NewTable)
                    Catch ex As Exception
                        transqlserver.Rollback()
                    Finally
                        NewTable = Nothing
                    End Try

                    EditDataSet(Me.LabInfo.Text, Me.cmbStoreOperate.Text, Me.cmbOutStoreType.Text, Me.cmbToStore1.Text, Me.cmbFromStore.Text, StorePlace, OperaterDate, PubUserName, DeliverNo, DeliverPerson, DeliverDate, DeliverCar, Remark)
                End If
            ElseIf Me.TabControl1.SelectedIndex = 2 Then
                If ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then


                    sql = "Delete Stor_ElementOut where BoNumB='" & Me.txtEleOutStoreNo.Text & "' and GoodsBarcode='*" & Me.txtEleBarcode.Text & "*'"
                    With sqlcmd
                        .Connection = sqlConn
                        .Transaction = transqlserver
                        .CommandType = CommandType.Text
                        .CommandText = sql
                        .ExecuteNonQuery()
                    End With
                    Dim NewTable As DataTable = ReturnTable(Me.txtEleOutStoreNo.Text, 1)

                    SqlBulk = New SqlClient.SqlBulkCopy(sqlConn, SqlBulkCopyOptions.Default, transqlserver)
                    SqlBulk.DestinationTableName = "Stor_ElementOut"
                    SqlBulk.BulkCopyTimeout = 100

                    Try
                        SqlBulk.WriteToServer(NewTable)
                    Catch ex As Exception
                        transqlserver.Rollback()
                        NewTable = Nothing
                        MsgBox("savetodatabase:" + ex.Message, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
                        Exit Sub
                    Finally
                        NewTable = Nothing
                    End Try

                End If
            End If
            transqlserver.Commit()
            sqlConn.Close()
            Me.DGV_Master.DataSource = MasterDS.Tables(0)
            Me.DGV_Master.CurrentCell = Me.DGV_Master.Rows(Me.DGV_Master.Rows.Count - 1).Cells("BoNum")
            SetGridRowBackColor(Me.DGV_Master, MasterDS)
            MsgBox(IIf(ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd, My.Resources.AddSuccess, My.resources.EditSuccess), MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
            ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp
            bFind = True
            MainForm.BtnEnable(bFind)
            SetEnable(False)
            GetToolEnable()
        Catch ex As Exception
            transqlserver.Rollback()
            MsgBox("savetodatabase:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Function number(ByVal k As String, ByVal kkk As String) As Integer
        Try
            Dim dsreadnumber As New DataSet
            Dim strsql As String = ""
            strsql = "select * from " & kkk & " where billtype='" & k & "'"
            dsreadnumber = ReturnDataset(strsql)
            If dsreadnumber.Tables(0).Rows.Count > 0 Then
                For Each drow As DataRow In dsreadnumber.Tables(0).Rows
                    number = drow("number")
                Next
            Else
                number = 1
            End If
        Catch ex As Exception
            MessageBox.Show(ex.ToString, "error", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End Try
    End Function

    Private Function updatenumber(ByVal k As String, ByVal kkk As String)
        Try
            Dim strsql As String = ""
            Dim tt = CInt(number("movenum", "number"))
            updatenumber = "update " & kkk & " set number='" & tt & "'+1  where billtype='" & k & "'"
        Catch ex As Exception
            MessageBox.Show(ex.ToString, "error", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End Try
    End Function

    Private Function updatenumberelement(ByVal k As String, ByVal kkk As String)
        Try
            Dim strsql As String = ""
            Dim tt = CInt(number("movenum", "number"))
            'updatenumberelement = "update " & kkk & " set number='" & tt & "' + '" + CInt(txtqty.Text) + " '  where billtype='" & k & "'"
        Catch ex As Exception
            MessageBox.Show(ex.ToString, "error", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End Try
    End Function

    Private Sub ComboBox2_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Try
            checkbarcode()
        Catch ex As Exception
            MessageBox.Show(ex.ToString, "error", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End Try

    End Sub

    Private Sub LoadPopfrmInfo()
        Dim sql As String = ""
        Dim m_Ds As New DataSet
        Dim mCount As Integer
        Try

            sql = "select Count(*) from Stor_TradeMaster where TradeType='-' and BoStatus in ('A','C')"

            m_Ds = ReturnDataset(sql)
            If m_Ds.Tables(0).Rows.Count > 0 Then

                mCount = Convert.ToInt64(m_Ds.Tables(0).Rows(0).Item(0))
                If mCount > 0 Then
                    With Popupfrm
                        .CloseButtonClickEnabled = True
                        .TitleClickEnabled = False
                        .TextClickEnabled = True
                        .DrawTextFocusRect = True
                        .KeepVisibleOnMouseOver = True
                        .TitleRectangle = New Rectangle(55, 20, 100, 30)
                        .ReShowOnMouseOver = False
                        AddHandler .TextClick, AddressOf PopupfrmQueryInfo
                        .Show("每日提醒", "你還有 [" & mCount & "] 單尚未審核,請趕快審核吧!", 500, 5000, 500)
                    End With
                End If

            End If
        Catch ex As Exception
            MsgBox("LoadPopfrmInfo:" & ex.Message, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        Finally
            m_Ds = Nothing
        End Try
    End Sub

    Public Sub PopupfrmQueryInfo(ByVal sender As Object, ByVal e As EventArgs)

        Try
            Dim sql As String = ""

            sql = "select a.BoNum,b.TradeType,c.InOrOutType,d.ToStore,e.FromStore,a.StorePlace,a.DeliverNo,a.DeliverPerson,a.DeliverDate,a.DeliverCar,BoStatus=f.ListA,"
            sql += " a.Remark,a.OperatePerson,a.OperateDate,a.CheckPerson,a.CheckDate  from Stor_TradeMaster a left join "
            sql += " (select a.BoNum,b.name as TradeType from Stor_TradeMaster a inner join Stor_tradecode b on a.TradeType=b.AddorNot where b.code='02') b on a.BoNum=b.BoNum left join "
            sql += " (select a.BoNum,b.ListA as InOrOutType from Stor_TradeMaster a inner join BSC_OtherDefineB b on a.InOrOutType=b.ListCode where b.ItemNo=58) c on a.BoNum=c.BoNum left join "
            sql += " (select a.BoNum,b.fShortName as ToStore from Stor_TradeMaster a inner join BSC_StoreHouse b on a.ToStore=b.fCode) d on a.BoNum=d.boNum left join "
            sql += " (select a.BoNum,b.fShortName as FromStore from Stor_TradeMaster a inner join BSC_StoreHouse b on a.FromStore=b.fCode) e on a.BoNum=e.BoNum inner join BSC_OtherDefineB f on a.BoStatus=f.ListCode"
            sql += " where f.ItemNo=16 and a.TradeType='-' and BoStatus in ('A','C')"

            MasterDS = ReturnDataset(sql)
            Me.DGV_Master.DataSource = MasterDS.Tables(0)
            bFind = MasterDS.Tables(0).Rows.Count > 0
            SetGridRowBackColor(Me.DGV_Master, MasterDS)
            GetToolEnable()

        Catch ex As Exception
            MsgBox("PopupfrmQueryInfo:" & ex.Message, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub



#End Region


#Region "SelfDefine Event"

    Private Sub BindDataGridViewMaster()
        Try
            Dim mTable As New DataTable
            With mTable

                .Columns.Add("bonum")
                .Columns.Add("tradetype")
                .Columns.Add("inorouttype")
                .Columns.Add("tostore")
                .Columns.Add("fromstore")
                .Columns.Add("storeplace")
                .Columns.Add("deliverno")
                .Columns.Add("deliverperson")
                .Columns.Add("deliverdate")
                .Columns.Add("delivercar")
                .Columns.Add("bostatus")
                .Columns.Add("remark")
                .Columns.Add("operateperson")
                .Columns.Add("operatedate")
                .Columns.Add("checkperson")
                .Columns.Add("checkdate")
            End With
            MasterDS = New DataSet
            MasterDS.Tables.Add(mTable)
            Me.DGV_Master.DataSource = MasterDS.Tables(0)

            With Me.DGV_Master
                For i As Integer = 0 To Me.DGV_Master.Columns.Count - 1
                    Dim mKey As String = .Columns(i).Name
                    Dim CaptionStr As String = BindHash(0).Item(mKey)
                    .Columns(i).HeaderText = CaptionStr
                Next
                .AllowUserToAddRows = False
                .AllowUserToDeleteRows = False
                .ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
                .SelectionMode = DataGridViewSelectionMode.FullRowSelect
                .MultiSelect = True
                .ReadOnly = True
            End With

        Catch ex As Exception
            MsgBox("BindDataGridViewA:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub BindDataGridViewDetail()
        Try
            Dim mtable As New DataTable
            With mtable
                .Columns.Add("ItemNo")
                .Columns.Add("PoNum")
                .Columns.Add("PoNumItem")
                .Columns.Add("GoodsBarCode")
                .Columns.Add("GoodsCode")
                .Columns.Add("SupperItem")
                .Columns.Add("GoodsEname")
                .Columns.Add("GoodsName")
                .Columns.Add("GoodsSpec")
                .Columns.Add("goodsamount", GetType(Decimal))
                .Columns.Add("Batch")
                .Columns.Add("storeplace")
                .Columns.Add("goodsstatus")
                .Columns.Add("goodsother")
                .Columns.Add("PackingNum")
            End With
            DetailDS = New DataSet
            DetailDS.Tables.Add(mtable)
            Me.DGV_Detail.DataSource = DetailDS.Tables(0)

            With Me.DGV_Sum
                .ReadOnly = True
                .AllowUserToAddRows = False
                .AllowUserToDeleteRows = False
                .ColumnHeadersVisible = False
                Me.DGV_Sum.Columns.Add("ItemNo", "")
                Me.DGV_Sum.Columns.Add("PoNum", "")
                Me.DGV_Sum.Columns.Add("PoNumItem", "")
                Me.DGV_Sum.Columns.Add("GoodsBarCode", "")
                Me.DGV_Sum.Columns.Add("GoodsCode", "")
                Me.DGV_Sum.Columns.Add("SupperItem", "")
                Me.DGV_Sum.Columns.Add("GoodsEname", "")
                Me.DGV_Sum.Columns.Add("GoodsName", "")
                Me.DGV_Sum.Columns.Add("GoodsSpec", "")
                Me.DGV_Sum.Columns.Add("goodsamount", "")
                Me.DGV_Sum.Columns.Add("Batch", "")
                Me.DGV_Sum.Columns.Add("storeplace", "")
                Me.DGV_Sum.Columns.Add("goodsstatus", "")
                Me.DGV_Sum.Columns.Add("goodsother", "")
                Me.DGV_Sum.Columns.Add("PackingNum", "")
                Me.DGV_Sum.Columns("GoodsBarCode").Visible = True
                .Columns("goodsamount").DefaultCellStyle.BackColor = Color.AliceBlue
                .Columns("goodsamount").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
                .Columns("PackingNum").ReadOnly = False
                .Columns("PackingNum").DefaultCellStyle.BackColor = Color.AliceBlue
                .Columns("PackingNum").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
                .Columns("ItemNo").Width = 55
                Dim GridRow As New DataGridViewRow
                Me.DGV_Sum.Rows.Add(GridRow)
            End With

            With DGV_Detail
                For i As Integer = 0 To DGV_Detail.Columns.Count - 1
                    Dim mkey As String = DGV_Detail.Columns(i).Name
                    Dim captionstr As String = BindHash(1).Item(mkey)
                    .Columns(i).HeaderText = captionstr
                Next
                .ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
                .MultiSelect = False
                .Columns("GoodsBarCode").Visible = True
                .Columns("goodsamount").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
                .Columns("goodsamount").DefaultCellStyle.BackColor = Color.AliceBlue
                .Columns("PackingNum").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
                .Columns("PackingNum").DefaultCellStyle.BackColor = Color.AliceBlue
                .Columns("Batch").ReadOnly = True
                .Columns("storeplace").ReadOnly = True
                .Columns("ItemNo").ReadOnly = True
                .Columns("ItemNo").Frozen = True
                .Columns("ItemNo").Width = 55
            End With

            SetGridWidth()
        Catch ex As Exception
            MsgBox("BindDataGridViewDetail:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub BindElementGridView()
        Dim mTable As New DataTable
        Try
            With mTable
                .Columns.Add("Element")
                .Columns.Add("Elementamount")
                .Columns.Add("ElementUnit")
                .Columns.Add("Elementbatch")
                .Columns.Add("StorePlace")
                .Columns.Add("ElementStatus")
            End With

            Me.dgv_Element.DataSource = mTable

            With Me.dgv_Element
                With Me.dgv_Element
                    For i As Integer = 0 To .Columns.Count - 1
                        Dim mKey As String = .Columns(i).Name
                        Dim CaptionStr As String = BindHash(2).Item(mKey)
                        .Columns(i).HeaderText = CaptionStr
                    Next
                    .AllowUserToAddRows = False
                    .AllowUserToDeleteRows = False
                    .ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
                End With
            End With
        Catch ex As Exception
            MsgBox("BindElementGridView:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        Finally
            mTable.Dispose()
            mTable = Nothing
        End Try

    End Sub

    Private Function BindHash(Optional ByVal index As Integer = 0) As Hashtable
        Try
            Dim mHash As New Hashtable
            With mHash
                Select Case index
                    Case 0
                        .Add("bonum", "出庫單號")
                        .Add("tradetype", "庫存操作")
                        .Add("inorouttype", "出庫類型")
                        .Add("tostore", "目的倉庫")
                        .Add("fromstore", "起源倉庫")
                        .Add("storeplace", "倉位")
                        .Add("deliverno", "送貨單號")
                        .Add("deliverperson", "送貨人")
                        .Add("deliverdate", "送貨日期")
                        .Add("delivercar", "送貨車號")
                        .Add("bostatus", "單據狀態")
                        .Add("remark", "備註")
                        .Add("operateperson", "操作員")
                        .Add("operatedate", "錄入時間")
                        .Add("checkperson", "審核人")
                        .Add("checkdate", "審核日期")
                    Case 1
                        .Add("ItemNo", "編號")
                        .Add("PoNum", "文件號")
                        .Add("PoNumItem", "項目編號")
                        .Add("GoodsBarCode", "貨品條碼")
                        .Add("GoodsCode", "貨品編碼")
                        .Add("SupperItem", "供應商編號")
                        .Add("GoodsEname", "英文名稱")
                        .Add("GoodsName", "貨品名稱")
                        .Add("GoodsSpec", "貨品規格")
                        .Add("goodsamount", "數量")
                        .Add("Batch", "批次")
                        .Add("storeplace", "存儲倉位")
                        .Add("goodsstatus", "狀態")
                        .Add("goodsother", "其他")
                        .Add("PackingNum", "件數")
                    Case 2
                        .Add("Element", "元件號")
                        .Add("Elementamount", "元件數量")
                        .Add("ElementUnit", "單位")
                        .Add("Elementbatch", "批次")
                        .Add("StorePlace", "庫位")
                        .Add("ElementStatus", "狀態")
                End Select
            End With
            Return mHash
        Catch ex As Exception
            Return Nothing
            MsgBox("ReturnHash:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Function

    Private Sub SetGridWidth()

        Try
            For i As Integer = 1 To Me.DGV_Detail.Columns.Count - 1
                Me.DGV_Sum.Columns(i).Width = Me.DGV_Detail.Columns(i).Width
            Next
        Catch ex As Exception
            MsgBox("SetGridWidth:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub LoadGoods()
        Try

            Dim sql As String
            sql = "select replace(a.Barcode,'*','') as BarCode,a.Code,ISNULL(a.Enname,'') as Enname ,a.ShortName,b.ColorCName as Color,c.SizeSName as Spec,a.IsElement from BSC_Goods a inner join BSC_ColorDefine b on a.Color=b.Colorcode inner join BSC_SizeDefine c on a.Spec=c.Sizecode;"
            GoodsDS = New DataSet
            GoodsDS = ReturnDataset(sql)
        Catch ex As Exception
            MsgBox("LoadGoods:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub LoadStoreType()
        Try
            Dim sql As String
            sql = "select * from Stor_tradecode order by code ;"
            sql += "select b.* from BSC_OtherDefineA a inner join BSC_OtherDefineB b on a.ID=b.ItemNo where a.ItemCode='OutStoreType';"
            sql += " select * from dbo.BSC_StoreHouse where fStatus=0;"
            sql += " select * from dbo.BSC_StoreHouse;"
            sql += "select b.* from BSC_OtherDefineA a inner join BSC_OtherDefineB b on a.ID=b.ItemNo where a.ItemCode='BillstatusDefine';"
            sql += "select * from dbo.BSC_Employee where fDeptID in (select ID from BSC_DEPT where fCode='" & PubCompanyCode & "')"

            StoreDS = New DataSet
            StoreDS = ReturnDataset(sql)

            Me.cmbStoreOperate.DisplayMember = "Name"
            Me.cmbStoreOperate.ValueMember = "AddOrNot"
            Me.cmbStoreOperate.DataSource = StoreDS.Tables(0)
            Me.cmbStoreOperate.DropDownStyle = ComboBoxStyle.DropDownList
            If cmbStoreOperate.Items.Count > 0 Then
                Me.cmbStoreOperate.SelectedIndex = 1
            End If

            Me.cmbStoreOperate.Enabled = False

            Me.cmbOutStoreType.DisplayMember = "ListA"
            Me.cmbOutStoreType.ValueMember = "Listcode"
            Me.cmbOutStoreType.DataSource = StoreDS.Tables(1)
            Me.cmbOutStoreType.DropDownStyle = ComboBoxStyle.DropDownList

            Me.cmbFromStore.DisplayMember = "fShortName"
            Me.cmbFromStore.ValueMember = "fCode"
            Me.cmbFromStore.DataSource = StoreDS.Tables(2)
            Me.cmbFromStore.DropDownStyle = ComboBoxStyle.DropDownList
            If Me.cmbFromStore.FindString(PubCompanyName) = -1 Then
                MsgBox("注意：[" & PubCompanyName & "], 資料未建立或目前為不可用狀態,建義設置該倉庫，在設置期間不能做出庫操作！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
            Else
                Me.cmbFromStore.SelectedIndex = Me.cmbFromStore.FindString(PubCompanyName)
            End If

            Me.cmbToStore1.DisplayMember = "fShortName"
            Me.cmbToStore1.ValueMember = "fCode"
            Me.cmbToStore1.DataSource = StoreDS.Tables(3)
            Me.cmbToStore1.DropDownStyle = ComboBoxStyle.DropDownList
            Me.cmbToStore1.Enabled = False

            Me.cmbBoStatus.DisplayMember = "ListA"
            Me.cmbBoStatus.ValueMember = "Listcode"
            Me.cmbBoStatus.DataSource = StoreDS.Tables(4)
            Me.cmbBoStatus.DropDownStyle = ComboBoxStyle.DropDownList
            Me.cmbBoStatus.SelectedIndex = 0
            Me.cmbBoStatus.Enabled = False

            Dim NewTable As DataTable = CType(Me.cmbFromStore.DataSource, DataTable)
            Me.cmbquerystore.DisplayMember = "fShortName"
            Me.cmbquerystore.ValueMember = "fCode"
            Me.cmbquerystore.DataSource = NewTable
            Me.cmbquerystore.SelectedIndex = -1

            Dim mTable As DataTable = CType(Me.cmbOutStoreType.DataSource, DataTable)
            Me.cmbqueryoperationtype.DisplayMember = "ListA"
            Me.cmbqueryoperationtype.ValueMember = "Listcode"
            Me.cmbqueryoperationtype.DataSource = mTable
            Me.cmbqueryoperationtype.SelectedIndex = -1

            Dim nTable As DataTable = CType(Me.cmbBoStatus.DataSource, DataTable)
            Me.cmbOrdeStatus.DisplayMember = "ListA"
            Me.cmbOrdeStatus.ValueMember = "Listcode"
            Me.cmbOrdeStatus.DataSource = nTable
            Me.cmbOrdeStatus.SelectedIndex = -1

            Me.cmbOperatePerson.DisplayMember = "fCName"
            Me.cmbOperatePerson.ValueMember = "fCode"
            Me.cmbOperatePerson.DataSource = StoreDS.Tables(5)
            Me.cmbOperatePerson.SelectedIndex = -1

            With combElementstatus
                .Items.Add("1" + Space(2) + "一級品")
                .Items.Add("2" + Space(2) + "二級品")
                .Items.Add("3" + Space(2) + "三級品")
                .Items.Add("4" + Space(2) + "次品")
                .DropDownStyle = ComboBoxStyle.DropDownList
                .SelectedIndex = 0
            End With

            With combElementunit
                .Items.Add("PC")
                .DropDownStyle = ComboBoxStyle.DropDownList
                .SelectedIndex = 0
            End With

        Catch ex As Exception
            MsgBox("LoadStoreType:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub BtnActionSave()
        Try
            savetodatabase()
        Catch ex As Exception
            MsgBox("BtnActionSave:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub AddtoDataset(ByVal MoveNum As String, ByVal tradetype As String, ByVal inorouttype As String, ByVal ToStoreHouse As String, ByVal fromstore As String, ByVal OperateDate As String, _
                            ByVal storeplace As String, ByVal deliverno As String, ByVal deliverperson As String, ByVal deliverdate As String, ByVal delivercar As String, ByVal Batch As String, ByVal BoStatus As String, ByVal remark As String, ByVal operateperson As String)
        Try
            If MasterDS Is Nothing Then Exit Sub
            Dim mRow As DataRow = MasterDS.Tables(0).NewRow
            mRow("BoNum") = MoveNum
            mRow("tradetype") = tradetype
            mRow("inorouttype") = inorouttype
            If Me.cmbOutStoreType.SelectedIndex = 2 Then
                mRow("tostore") = ToStoreHouse
            Else
                mRow("tostore") = ""
            End If
            mRow("fromstore") = fromstore
            mRow("storeplace") = storeplace
            mRow("deliverno") = deliverno
            mRow("deliverperson") = deliverperson
            mRow("deliverdate") = deliverdate
            mRow("delivercar") = delivercar
            mRow("BoStatus") = BoStatus
            mRow("remark") = remark
            mRow("operateperson") = operateperson
            mRow("operatedate") = OperateDate
            MasterDS.Tables(0).Rows.Add(mRow)
            MasterDS.AcceptChanges()

        Catch ex As Exception
            MsgBox("AddtoDataset:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub EditDataSet(ByVal MoveNum As String, ByVal tradetype As String, ByVal inorouttype As String, ByVal ToStoreHouse As String, ByVal fromstore As String, ByVal storeplace As String, ByVal OperateDate As String, _
                            ByVal operateperson As String, ByVal DeliverNo As String, ByVal deliverperson As String, ByVal deliverdate As String, ByVal delivercar As String, ByVal Remark As String)
        Try
            Dim Rows() As DataRow = MasterDS.Tables(0).Select("BoNum='" & MoveNum & "'")
            If Rows.Length > 0 Then
                For Each mRow As DataRow In Rows
                    mRow("tradetype") = tradetype
                    mRow("inorouttype") = inorouttype
                    mRow("tostore") = ToStoreHouse
                    mRow("fromstore") = fromstore
                    mRow("storeplace") = storeplace
                    mRow("deliverno") = DeliverNo
                    mRow("deliverperson") = deliverperson
                    mRow("deliverdate") = deliverdate
                    mRow("delivercar") = delivercar
                    mRow("DeliverNo") = DeliverNo
                    mRow("remark") = Remark
                    mRow("operateperson") = operateperson
                    mRow("operatedate") = OperateDate
                Next
            End If
            MasterDS.AcceptChanges()
        Catch ex As Exception
            MsgBox("AddtoDataset:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Function DeleteDataset(ByVal BoNum As String) As Boolean
        Try
            Dim sql As String
            'sql = " UPDATE SAL_IAA SET STATUS ='B' WHERE VOUCHER_NO IN "
            'sql += "(SELECT A.PONUM FROM STOR_TRADEDETAIL A LEFT JOIN STOR_TRADEMASTER B ON A.BONUM = B.BONUM WHERE A.BONUM = '" & BoNum & "' AND INOROUTTYPE ='03')"
            sql += "Delete Stor_TradeMaster where BoNum='" & BoNum & "';"
            sql += "Delete Stor_TradeDetail where BoNum='" & BoNum & "'"
            ReturnObject(sql)
            Dim Rows() As DataRow = MasterDS.Tables(0).Select("BoNum='" & BoNum & "'")
            If Rows.Length > 0 Then
                MasterDS.Tables(0).Rows.Remove(Rows(0))
                MasterDS.AcceptChanges()
            End If
            Me.DGV_Master.DataSource = MasterDS.Tables(0)
            Return True
        Catch ex As Exception
            MsgBox("DeleteDataset:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Function

    Private Sub SetEnable(ByVal b As Boolean)
        'Me.btnelement.Enabled = b
        'Me.lstviewelement.Enabled = b
        Me.txtElementcount.Enabled = False
        'Me.combElementunit.Enabled = b
        'Me.combElementstatus.Enabled = b
        'Me.txtElementNo.Enabled = b
        Me.cmbFromStore.Enabled = False
        Me.cmbOutStoreType.Enabled = b
        Me.txtStorePlace1.Enabled = b
        Me.txtStatus.Enabled = b
        Me.txtDocumentNo.Enabled = b
        Me.txtDeliverCar.Enabled = b
        Me.DateTimePicker2.Enabled = b
        Me.txtDeliverPerson.Enabled = b
        Me.txtRemark.Enabled = b
        Me.RadioButton1.Enabled = b
        Me.RadioButton2.Enabled = False
        Me.txtGoodsBarcode.Enabled = b
        Me.cmbBatch.Enabled = UncheckEnable = True And Me.RadioButton2.Checked = True
        Me.cmbStorePlace.Enabled = False
        Me.cmbGoodsBarcode.Enabled = UncheckEnable = True And Me.RadioButton2.Checked = True
        Me.GoodsCount.Enabled = UncheckEnable = True And Me.RadioButton2.Checked = True
        Me.txtSaleOrdeNo.Enabled = UncheckEnable = True And Me.RadioButton2.Checked = True
        Me.txtSaleOrdeNo.Enabled = b And Me.cmbOutStoreType.SelectedIndex = 6 And (ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit)
        With Me.DGV_Detail
            .AllowUserToAddRows = b
        End With
    End Sub

    Private Sub ClearText()
        Me.LabInfo.Text = ""
        Me.txtStorePlace1.Text = ""
        Me.txtStatus.Text = ""
        Me.txtDocumentNo.Text = ""
        Me.txtSaleOrdeNo.Text = ""
        Me.txtDeliverCar.Text = ""
        Me.txtRemark.Text = ""
        Me.GoodsCount.Text = ""
        RadioButton2.Checked = False
        Me.DGV_Sum.Rows(0).Cells("goodsamount").Value = "0.00"
        Me.DGV_Sum.Rows(0).Cells("PackingNum").Value = "0.00"
        Me.DateTimePicker2.Value = ServerDate
        If Me.TabControl1.SelectedIndex = 1 Then
            Me.cmbFromStore.SelectedIndex = Me.cmbFromStore.FindString(PubCompanyName)
            Me.cmbBoStatus.SelectedIndex = 0
            Me.cmbOutStoreType.SelectedIndex = 0
        End If
        If DetailDS.Tables(0).Rows.Count > 0 Then
            DetailDS.Tables(0).Rows.Clear()
            Me.DGV_Detail.DataSource = DetailDS.Tables(0)
        End If

    End Sub

    Private Function IsAmountClose() As Boolean

        Try

            Dim sql As String = ""
            Dim m_Ds As New DataSet
            IsClose = True
            sql = "select * from BSC_SystemProfile where FKey like '%" & PubCompanyCode & "%'"
            m_Ds = ReturnDataset(sql)
            If m_Ds.Tables(0).Rows.Count > 0 Then
                PeriodData = m_Ds.Tables(0).Rows(0).Item("FValue")
                IsClose = CType(m_Ds.Tables(0).Rows(1).Item("FValue"), Boolean)
            End If
            Return IsClose
        Catch ex As Exception
            MsgBox("IsAmountClose" & ex.Message, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Function

    Private Sub FillText(ByVal BoNum As String)
        Try
            If MasterDS Is Nothing Then Exit Sub
            Dim Rows() As DataRow = MasterDS.Tables(0).Select("BoNum='" & BoNum & "'")
            Dim BarCode As String = ""
            Dim sql As String
            If Rows.Length > 0 Then
                Me.LabInfo.Text = BoNum
                Me.cmbOutStoreType.SelectedIndex = cmbOutStoreType.FindString(Rows(0).Item("InOrOutType") & "")
                Me.cmbFromStore.SelectedIndex = Me.cmbFromStore.FindString(Rows(0).Item("FromStore") & "")
                If Rows(0).Item("ToStore") & "" = "" Then
                    Me.cmbToStore1.SelectedIndex = -1
                Else
                    Me.cmbToStore1.SelectedIndex = Me.cmbToStore1.FindString(Rows(0).Item("ToStore") & "")
                End If
                Me.cmbBoStatus.SelectedIndex = Me.cmbBoStatus.FindString(Rows(0).Item("BoStatus") & "")
                Me.txtStorePlace1.Text = Rows(0).Item("StorePlace") & ""
                Me.txtDocumentNo.Text = Rows(0).Item("DeliverNo") & ""
                If Rows(0).Item("DeliverDate") & "" = "" Then
                Else
                    Me.DateTimePicker2.Value = CDate(Rows(0).Item("DeliverDate") & "")
                End If
                Me.txtDeliverPerson.Text = Rows(0).Item("DeliverPerson") & ""
                Me.txtDeliverCar.Text = Rows(0).Item("DeliverCar") & ""
                Me.txtRemark.Text = Rows(0).Item("Remark") & ""
            End If
            sql = "select a.ItemNo,a.PoNum,a.PoNumItem,a.GoodsBarCode,a.GoodsCode,a.SupperItem,a.GoodsName,a.GoodsEname,a.GoodsSpec,a.Goodsamount,a.Batch,a.StorePlace,a.GoodsOther,isnull(PackingNum,1)*Goodsamount as PackingNum Into #AA from V_OutStoreDetail a where a.BoNum='" & BoNum & "' ;" & vbCrLf
            sql += "select * from #AA ;" & vbCrLf
            sql += "drop table #AA ;"
            DetailDS = ReturnDataset(sql)
            Me.DGV_Detail.DataSource = DetailDS.Tables(0)
            If DetailDS.Tables(0).Rows.Count > 0 Then
                Me.DGV_Sum.Rows(0).Cells("goodsamount").Value = Format(DetailDS.Tables(0).Compute("sum(goodsamount)", ""), "#0.00")
                Me.DGV_Sum.Rows(0).Cells("PackingNum").Value = Format(DetailDS.Tables(0).Compute("sum(PackingNum)", ""), "#0.00")

            Else
                Me.DGV_Sum.Rows(0).Cells("goodsamount").Value = "0.00"
                Me.DGV_Sum.Rows(0).Cells("PackingNum").Value = "0.00"
            End If
            If DetailDS.Tables(0).Rows.Count > 0 Then
                If DetailDS.Tables(0).Rows(0).Item("PoNum") Is DBNull.Value Or DetailDS.Tables(0).Rows(0).Item("PoNum") & "" = "" Then
                    If Me.DGV_Detail.Columns("PoNum").Visible = True Then
                        Me.DGV_Detail.Columns("PoNum").Visible = False
                        Me.DGV_Sum.Columns("PoNum").Visible = False
                    End If
                    If Me.DGV_Detail.Columns("PoNumItem").Visible = True Then
                        Me.DGV_Detail.Columns("PoNumItem").Visible = False
                        Me.DGV_Sum.Columns("PoNumItem").Visible = False
                    End If
                Else
                    If Me.DGV_Detail.Columns("PoNum").Visible = False Then
                        Me.DGV_Detail.Columns("PoNum").Visible = True
                        Me.DGV_Sum.Columns("PoNum").Visible = True
                    End If
                    If Me.DGV_Detail.Columns("PoNumItem").Visible = False Then
                        Me.DGV_Detail.Columns("PoNumItem").Visible = True
                        Me.DGV_Sum.Columns("PoNumItem").Visible = True
                    End If
                End If
            End If
        Catch ex As Exception
            MsgBox("FillText:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub FillElement(ByVal BarCode As String)

        Try

            If Me.DGV_Detail.CurrentRow.Cells(0).Value Is DBNull.Value Then
                Exit Sub
            End If
            Dim CurrentID As String = Me.DGV_Detail.CurrentRow.Cells(0).Value
            Dim Rows() As DataRow = DetailDS.Tables(0).Select("ItemNo='" & CurrentID & "' and GoodsBarCode='" & BarCode & "'")
            Dim GoodsRows() As DataRow = GoodsDS.Tables(0).Select("BarCode='" & BarCode & "'")
            Dim sql As String = ""

            Me.txtEleOutStoreNo.Text = ""
            Me.txtEleBarcode.Text = ""
            Me.txtEleSuppercode.Text = ""
            Me.txtEleEnname.Text = ""
            Me.txtEleCnname.Text = ""
            Me.txtEleColor.Text = ""
            Me.txtEleSpec.Text = ""
            Me.txtEleOutStoreCount.Text = ""
            Me.txtEleOutStoreBatch.Text = ""
            Me.txtEleStoreage.Text = ""


            If Rows.Length > 0 Then
                Me.txtEleOutStoreNo.Text = Me.LabInfo.Text
                Me.txtEleBarcode.Text = Rows(0).Item("GoodsBarCode")
                If Rows(0).Item("SupperItem") & "" = "" Then
                Else
                    Me.txtEleSuppercode.Text = Rows(0).Item("SupperItem")
                End If
                If GoodsRows(0).Item("Enname") & "" = "" Then
                Else
                    Me.txtEleEnname.Text = GoodsRows(0).Item("Enname")
                End If
                If Rows(0).Item("GoodsName") & "" = "" Then
                Else
                    Me.txtEleCnname.Text = Rows(0).Item("GoodsName")
                End If
                If Rows(0).Item("GoodsEname") & "" = "" Then
                Else
                    Me.txtEleColor.Text = Rows(0).Item("GoodsEname")
                End If

                Me.txtEleSpec.Text = Rows(0).Item("GoodsSpec")
                Me.txtEleOutStoreCount.Text = Rows(0).Item("goodsamount")
                Me.txtEleOutStoreBatch.Text = Rows(0).Item("Batch")
                Me.txtEleStoreage.Text = Rows(0).Item("storeplace")
            End If

            sql = "select * from Stor_ElementOut where GoodsBarcode='*" & BarCode & "*' and BoNumb='" & Me.LabInfo.Text & "'"
            Dim mDs As New DataTable
            mDs = ReturnDataTable(sql)
            Try
                Me.dgv_Element.DataSource = mDs
            Catch ex As Exception
                mDs = Nothing
            Finally
                mDs.Dispose()
            End Try

        Catch ex As Exception
            MsgBox("FillElement:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub FillDataGridViewelement(ByVal MoveNum As String)
        Try
            Dim sql As String
            sql = "select Element,elementamount,elementUnit,elementbatch,storeplace,elementstatus From stor_element where BonumA ='" & MoveNum & "'"
            dselement = New DataSet
            dselement = ReturnDataset(sql)
            'DataGridViewelement.DataSource = dselement.Tables(0)
        Catch ex As Exception
            MsgBox("FillDataGridViewelement:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub GetToolEnable()
        Try
            With MainForm
                .ToolStripAdd.Enabled = AddEnable
                .ToolStripEdit.Enabled = EditEnable And bFind = True
                .ToolStripDelete.Enabled = DeleteEnable And bFind = True
                .ToolStripPrint.Enabled = PrintEnable
                .ToolStripImport.Enabled = ImportEnable
                .ToolStripExport.Enabled = ExportEnable
                .ToolStripFind.Enabled = FindEnable
                .ToolStripCheck.Enabled = CheckEnable
                .ToolStripUnCheck.Enabled = UncheckEnable
                .ToolStripComplete.Enabled = CompleteEnable
                .AddToolStripMenuItem.Enabled = .ToolStripAdd.Enabled
                .Edit1ToolStripMenuItem.Enabled = .ToolStripEdit.Enabled
                .DelToolStripMenuItem.Enabled = .ToolStripDelete.Enabled
                .SaveToolStripMenuItem.Enabled = .ToolStripSave.Enabled
                .CancelToolStripMenuItem.Enabled = .ToolStripCancel.Enabled
                .PrintToolStripMenuItem.Enabled = .ToolStripPrint.Enabled
                .ExportToolStripMenuItem.Enabled = .ToolStripImport.Enabled
                .ImportToolStripMenuItem.Enabled = .ToolStripExport.Enabled
                .FilterToolStripMenuItem.Enabled = .ToolStripFilter.Enabled
            End With

        Catch ex As Exception
            MsgBox("GetToolEnable:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub SetToolEnable()

        If Me.DGV_Master.CurrentRow Is Nothing Then Exit Sub

        Dim ShopNo As String = Me.DGV_Master.CurrentRow.Cells("FromStore").Value
        Dim DeliverDate As String = Me.DGV_Master.CurrentRow.Cells("DeliverDate").Value.ToString.Replace("-", "").Substring(0, 6)


        If Me.DGV_Master.Rows.Count > 0 Then
            If Me.DGV_Master.CurrentRow.Cells("BoStatus").Value = "保存" Then
                MainForm.ToolStripPrint.Enabled = True
                If ShopNo = PubCompanyName Then
                    MainForm.ToolStripCheck.Enabled = True And CheckEnable = True
                    MainForm.ToolStripUnCheck.Enabled = False
                    MainForm.ToolStripComplete.Enabled = False
                    MainForm.ToolStripDelete.Enabled = True And DeleteEnable = True
                    MainForm.ToolStripEdit.Enabled = True And EditEnable = True
                Else
                    MainForm.ToolStripCheck.Enabled = False
                    MainForm.ToolStripUnCheck.Enabled = False
                    MainForm.ToolStripComplete.Enabled = False
                    MainForm.ToolStripDelete.Enabled = False
                    MainForm.ToolStripEdit.Enabled = False
                End If
            ElseIf Me.DGV_Master.CurrentRow.Cells("BoStatus").Value = "核准" Then
                If ShopNo = PubCompanyName Then
                    MainForm.ToolStripPrint.Enabled = True
                    MainForm.ToolStripCheck.Enabled = False
                    If DeliverDate < PeriodData Then
                        MainForm.ToolStripUnCheck.Enabled = False
                    Else
                        MainForm.ToolStripUnCheck.Enabled = True And UncheckEnable = True
                    End If
                    MainForm.ToolStripComplete.Enabled = True And CompleteEnable = True
                    MainForm.ToolStripDelete.Enabled = False
                    MainForm.ToolStripEdit.Enabled = False
                Else
                    MainForm.ToolStripPrint.Enabled = True
                    MainForm.ToolStripCheck.Enabled = False
                    MainForm.ToolStripUnCheck.Enabled = False
                    MainForm.ToolStripComplete.Enabled = False
                    MainForm.ToolStripDelete.Enabled = False
                    MainForm.ToolStripEdit.Enabled = False
                End If
            ElseIf Me.DGV_Master.CurrentRow.Cells("BoStatus").Value = "反核准" Then
                MainForm.ToolStripPrint.Enabled = True
                If ShopNo = PubCompanyName Then
                    MainForm.ToolStripCheck.Enabled = True And CheckEnable = True
                    MainForm.ToolStripUnCheck.Enabled = False
                    MainForm.ToolStripComplete.Enabled = False
                    MainForm.ToolStripDelete.Enabled = True And DeleteEnable = True And UncheckEnable = True
                    MainForm.ToolStripEdit.Enabled = True And EditEnable = True
                Else
                    MainForm.ToolStripCheck.Enabled = False
                    MainForm.ToolStripUnCheck.Enabled = False
                    MainForm.ToolStripComplete.Enabled = False
                    MainForm.ToolStripDelete.Enabled = False
                    MainForm.ToolStripEdit.Enabled = False
                End If
            ElseIf Me.DGV_Master.CurrentRow.Cells("BoStatus").Value = "結案" Then
                MainForm.ToolStripPrint.Enabled = True
                MainForm.ToolStripCheck.Enabled = False
                MainForm.ToolStripUnCheck.Enabled = False
                MainForm.ToolStripComplete.Enabled = False
                MainForm.ToolStripDelete.Enabled = False
                MainForm.ToolStripEdit.Enabled = False
            End If
        End If

    End Sub

    Private Sub ExportDeliverNo(ByVal mIndex As Integer)

        Dim DeliverNo As String = ""
        Dim DeliverNo1 As String = ""
        Dim sql As String = ""
        Dim sqlstr As String = ""
        Dim WhereStr As String = ""
        Dim Batch As String = ""
        Dim StorePlace As String = ""
        Dim GoodsCount As Double = 0
        Dim ExistCount As Double = 0
        Dim m_DS As New DataSet
        Dim mDs As New DataSet
        Dim Frm_ExportData As New Frm_ExportData
        Dim Frm_SelectInv As New Frm_SelectInv
        Try
            If Me.cmbOutStoreType.SelectedIndex = 4 Then
                Frm_SelectInv.ShowDialog()
                If Frm_SelectInv.SaleOrdeNo Is Nothing Then
                    Exit Sub
                End If
                DeliverNo = Frm_SelectInv.SaleOrdeNo
            Else
                Frm_ExportData.LoadFirstTree(mIndex)
                Frm_ExportData.ShowDialog()
                If Frm_ExportData.LabPoNum.Text Is Nothing Then
                    Exit Sub
                End If
                DeliverNo = Frm_ExportData.LabPoNum.Text
            End If

            If DeliverNo.Length <= 0 Then Exit Sub
            If DeliverNo.StartsWith("^") Then
                DeliverNo = DeliverNo.Remove(0, 1)
            End If
            If DeliverNo.EndsWith("^") Then
                DeliverNo = DeliverNo.Remove(DeliverNo.Length - 1, 1)
            End If
            For i As Integer = 0 To DeliverNo.Split("^").Length - 1
                DeliverNo1 += "'" & DeliverNo.Split("^")(i) & "',"
            Next
            If DeliverNo1.Length > 0 Then
                If DeliverNo1.EndsWith(",") Then
                    DeliverNo1 = DeliverNo1.Remove(DeliverNo1.Length - 1, 1)
                End If
            End If
            Select Case mIndex
                Case 0
                Case 1
                Case 2
                Case 3
                Case 4


                    WhereStr = " and isnull(c.fVirtual,'')<>1 and isnull(c.fBuJian,'')<>1"

                    sql = "select b.fSaleOrdeNo,b.ItemNo,replace(b.fGoodsBarCode,'*','') as fGoodsBarCode,c.Code,c.SupperItem,c.Enname,c.Cnname,d.ColorCname as Color,e.SizeSName as Spec,b.fTotal from DeliverGoodsDetail a inner join DeliverGoodsInfo b on a.fDeliverID=b.fDeliverId "
                    sql += " and a.fSaleOrdeNo=b.fSaleOrdeNo left join dbo.BSC_Goods c on b.fGoodsBarcode=c.barCode"
                    sql += " left join dbo.BSC_ColorDefine d on c.Color=d.colorCode"
                    sql += " left join dbo.BSC_SizeDefine e on c.Spec=e.SizeCode where 1=1 and b.fSaleOrdeNo in (" & DeliverNo1 & ")"
                    m_DS = ReturnDataset(sql)

                    If m_DS.Tables(0).Rows.Count > 0 Then

                        Dim NewRow As DataRow

                        For Each mRow As DataRow In m_DS.Tables(0).Rows
                            NewRow = DetailDS.Tables(0).NewRow

                            Dim Rows() As DataRow = DetailDS.Tables(0).Select("PoNum='" & mRow("fSaleOrdeNo") & "' and GoodsBarCode='" & mRow("fGoodsBarCode") & "'")
                            If Rows.Length > 0 Then
                                MsgBox("單號 [" & mRow("fSaleOrdeNo") & "] 已經存在列表中！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                                Exit For
                            End If
                            NewRow("ItemNo") = Format(DetailDS.Tables(0).Rows.Count + 1, "000")
                            NewRow("PoNum") = mRow("fSaleOrdeNo") & ""
                            NewRow("PoNumItem") = mRow("ItemNo") & ""
                            NewRow("GoodsBarCode") = mRow("fGoodsBarCode") & ""
                            NewRow("GoodsCode") = mRow("Code") & ""
                            NewRow("SupperItem") = mRow("SupperItem") & ""
                            NewRow("GoodsName") = mRow("Cnname") & ""
                            NewRow("GoodsEname") = mRow("Enname") & ""
                            NewRow("GoodsSpec") = mRow("Spec") & ""

                            sqlstr = "select a.Period,b.fShortName as StoreHouse,a.BarCode,a.Batch,a.StorePlace,a.Goodsamount from  (select Period,StoreHouse,replace(BarCode,'*','') as BarCode,Batch,StorePlace,sum(Goodsamount) as Goodsamount from V_VisualStoreQuery group by StoreHouse,Period,barcode,Batch,StorePlace) a "
                            sqlstr += " inner join BSC_StoreHouse b on a.StoreHouse=b.fCode left join BSC_Storage c on a.StorePlace=c.fStorageId where StoreHouse='" & PubCompanyCode & "' and isnull(a.Goodsamount,0.00)>0 " & WhereStr & " and isnull(a.BarCode,'')='" & mRow("fGoodsBarCode") & "' order by substring(Batch,4,3),substring(Batch,1,3),Goodsamount"
                            mDs = ReturnDataset(sqlstr)
                            If mDs.Tables(0).Rows.Count > 0 Then

                                For j As Integer = 0 To mDs.Tables(0).Rows.Count - 1
                                    Batch = mDs.Tables(0).Rows(j).Item("Batch")
                                    StorePlace = mDs.Tables(0).Rows(j).Item("StorePlace")
                                    GoodsCount = Convert.ToDouble(mDs.Tables(0).Rows(j).Item("Goodsamount"))
                                    Dim nRows() As DataRow = DetailDS.Tables(0).Select("GoodsBarCode='" & mRow("fGoodsBarCode") & "' and Batch='" & Batch & "' and storeplace='" & StorePlace & "'")
                                    If nRows.Length > 0 Then
                                        For i As Integer = 0 To nRows.Length - 1
                                            ExistCount += Convert.ToDouble(nRows(i).Item("goodsamount"))
                                        Next
                                    End If
                                    If ExistCount >= GoodsCount Then
                                        Continue For
                                    Else
                                        NewRow("Batch") = Batch
                                        NewRow("storeplace") = StorePlace
                                        DetailDS.Tables(0).Rows.Add(NewRow)
                                        Exit For
                                    End If
                                Next
                            Else
                                MsgBox("貨品 [" & mRow("SupperItem") & "] 沒有倉存,請補充倉存，再做出庫！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                            End If
                        Next
                        DetailDS.AcceptChanges()
                    End If
            End Select
            Me.DGV_Detail.DataSource = DetailDS.Tables(0)
            If DetailDS.Tables(0).Rows.Count > 0 Then
                Me.DGV_Detail.Focus()
                Me.DGV_Detail.CurrentCell = Me.DGV_Detail.Rows(Me.DGV_Detail.CurrentRow.Index).Cells("goodsamount")
            End If
        Catch ex As Exception
            MsgBox("ActionImport:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        Finally
            Frm_ExportData.Dispose()
            Frm_SelectInv.Dispose()
            m_DS.Dispose()
            mDs.Dispose()
        End Try

    End Sub

    Private Sub AddDataToGrid(ByVal BarCode As String)

        Dim m_Ds As New DataSet
        Try
            Dim Str() As String = BarCode.Split("^")
            Dim WhereStr As String = ""
            Dim Filters As String = ""
            Dim SumCount As Double = 0
            Dim sql As String

            For i As Integer = 0 To Str.Length - 1
                If Str(i).Length > 0 Then
                    If Me.cmbOutStoreType.SelectedIndex = 1 Then
                        'WhereStr = " and isnull(e.fVirtual,'')=1"
                    Else
                        WhereStr = " and isnull(e.fVirtual,'')<>1 and isnull(e.fBuJian,'')<>1"
                    End If
                    sql = "select a.Period,a.StoreHouse,replace(a.Barcode,'*','') as Barcode,a.Batch,a.StorePlace,a.Goodsamount,b.Code,b.SupperItem,b.Enname,b.Cnname,c.ColorSName as Color,d.SizeSName as Spec from "
                    sql += " (select Period,StoreHouse,BarCode,Batch,StorePlace,sum(Goodsamount) as Goodsamount from V_VisualStoreQuery   group by StoreHouse,Period,barcode,Batch,StorePlace) a"
                    sql += " inner join BSC_Goods b on a.BarCode=b.BarCode"
                    sql += " inner join BSC_ColorDefine c on b.Color=c.ColorCode "
                    sql += " inner join BSC_SizeDefine d on b.Spec=d.SizeCode "
                    sql += " left join BSC_Storage e on a.StorePlace=e.fStorageId"
                    sql += " where a.StoreHouse='" & PubCompanyCode & "' and isnull(a.Goodsamount,0.00)>0" & WhereStr & " and isnull(a.BarCode,'')='*" & Str(i) & "*' order by substring(Batch,4,3),substring(Batch,1,3),Goodsamount"

                    m_Ds = ReturnDataset(sql)
                    If m_Ds.Tables(0).Rows.Count > 0 Then
                        For Each mRow As DataRow In m_Ds.Tables(0).Rows
                            Dim NewRow As DataRow = DetailDS.Tables(0).NewRow
                            Dim Rows() As DataRow = DetailDS.Tables(0).Select("GoodsBarCode='" & mRow("BarCode") & "' and Batch='" & mRow("batch") & "' and storeplace='" & mRow("storeplace") & "'")
                            Filters = "GoodsBarcode='" & mRow("BarCode") & "' and Batch='" & mRow("batch") & "' and StorePlace='" & mRow("storeplace") & "'"
                            If DetailDS.Tables(0).Compute("sum(Goodsamount)", Filters) Is System.DBNull.Value Then
                                SumCount = 0.0
                            Else
                                SumCount = Convert.ToDouble(DetailDS.Tables(0).Compute("sum(Goodsamount)", Filters))
                            End If
                            If SumCount >= mRow("Goodsamount") Then
                                Continue For
                            End If
                            If Rows.Length > 0 Then
                                Dim ItemNo As String = Rows(0).Item("GoodsBarCode") & ""
                                Dim RowIndex As Integer = 0
                                For j As Integer = 0 To DetailDS.Tables(0).Rows.Count - 1
                                    If DetailDS.Tables(0).Rows(j).Item("GoodsBarCode").ToString.ToLower = ItemNo.ToLower Then
                                        RowIndex = j
                                        Exit For
                                    End If
                                Next
                                If Me.cmbOutStoreType.SelectedIndex = 4 Then
                                    NewRow("ItemNo") = Format(DetailDS.Tables(0).Rows.Count + 1, "000")
                                    NewRow("GoodsBarCode") = mRow("BarCode") & ""
                                    NewRow("GoodsCode") = mRow("Code") & ""
                                    NewRow("SupperItem") = mRow("SupperItem") & ""
                                    NewRow("GoodsName") = mRow("Cnname") & ""
                                    NewRow("GoodsEname") = mRow("Enname") & ""
                                    NewRow("GoodsSpec") = mRow("Spec") & ""
                                    NewRow("Batch") = mRow("batch") & ""
                                    NewRow("storeplace") = mRow("storeplace") & ""
                                    DetailDS.Tables(0).Rows.Add(NewRow)
                                Else
                                    MsgBox("貨品 [" & mRow("BarCode") & "] 已經存在列表中！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                                    Me.DGV_Detail.Focus()
                                    Me.DGV_Detail.CurrentCell = Me.DGV_Detail.Rows(RowIndex).Cells("goodsamount")
                                    Exit Sub
                                End If

                            Else
                                NewRow("ItemNo") = Format(DetailDS.Tables(0).Rows.Count + 1, "000")
                                NewRow("GoodsBarCode") = mRow("BarCode") & ""
                                NewRow("GoodsCode") = mRow("Code") & ""
                                NewRow("SupperItem") = mRow("SupperItem") & ""
                                NewRow("GoodsName") = mRow("Cnname") & ""
                                NewRow("GoodsEname") = mRow("Enname") & ""
                                NewRow("GoodsSpec") = mRow("Spec") & ""
                                NewRow("Batch") = mRow("batch") & ""
                                NewRow("storeplace") = mRow("storeplace") & ""
                                DetailDS.Tables(0).Rows.Add(NewRow)
                            End If
                            Exit For
                        Next
                    End If
                End If
            Next
            DetailDS.AcceptChanges()
            Me.DGV_Detail.DataSource = DetailDS.Tables(0)
            For i As Int16 = 0 To Me.DGV_Detail.Rows.Count - 2
                If Me.DGV_Detail.Rows(i).IsNewRow = False Then
                    If Me.DGV_Detail.Rows(i).Cells("GoodsBarCode").Value Is DBNull.Value Then
                        Me.DGV_Detail.Rows.RemoveAt(i)
                    End If
                End If
            Next
            If DetailDS.Tables(0).Rows.Count > 0 Then
                Me.DGV_Detail.Focus()
                Me.DGV_Detail.CurrentCell = Me.DGV_Detail.Rows(Me.DGV_Detail.CurrentRow.Index).Cells("goodsamount")
            End If
        Catch ex As Exception
            MsgBox("AddDataToGrid:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub ImportAddDataToGrid(ByVal BarCode As String)

        Dim m_Ds As New DataSet
        Try
            Dim Str() As String = BarCode.Split("^")
            Dim WhereStr As String = ""
            Dim Filters As String = ""
            Dim SumCount As Double = 0
            Dim sql As String

            For i As Integer = 0 To Str.Length - 1
                If Str(i).Length > 0 Then
                    If Me.cmbOutStoreType.SelectedIndex = 1 Then
                        'WhereStr = " and isnull(e.fVirtual,'')=1"
                    Else
                        WhereStr = " and isnull(e.fVirtual,'')<>1 and isnull(e.fBuJian,'')<>1"
                    End If
                    sql = "select a.Period,a.StoreHouse,replace(a.Barcode,'*','') as Barcode,a.Batch,a.StorePlace,a.Goodsamount,b.Code,b.SupperItem,b.Enname,b.Cnname,c.ColorSName as Color,d.SizeSName as Spec from "
                    sql += " (select Period,StoreHouse,BarCode,Batch,StorePlace,sum(Goodsamount) as Goodsamount from V_VisualStoreQuery   group by StoreHouse,Period,barcode,Batch,StorePlace) a"
                    sql += " inner join BSC_Goods b on a.BarCode=b.BarCode"
                    sql += " inner join BSC_ColorDefine c on b.Color=c.ColorCode "
                    sql += " inner join BSC_SizeDefine d on b.Spec=d.SizeCode "
                    sql += " left join BSC_Storage e on a.StorePlace=e.fStorageId"
                    sql += " where a.StoreHouse='" & PubCompanyCode & "' and isnull(a.Goodsamount,0.00)>0" & WhereStr & " and isnull(a.BarCode,'')='*" & Str(i) & "*' order by substring(Batch,4,3),substring(Batch,1,3),Goodsamount;"



                    m_Ds = ReturnDataset(sql)
                    If m_Ds.Tables(0).Rows.Count > 0 Then
                        For Each mRow As DataRow In m_Ds.Tables(0).Rows
                            Dim NewRow As DataRow = DetailDS.Tables(0).NewRow
                            Dim Rows() As DataRow = DetailDS.Tables(0).Select("GoodsBarCode='" & mRow("BarCode") & "' and Batch='" & mRow("batch") & "' and storeplace='" & mRow("storeplace") & "'")
                            Filters = "GoodsBarcode='" & mRow("BarCode") & "' and Batch='" & mRow("batch") & "' and StorePlace='" & mRow("storeplace") & "'"
                            If DetailDS.Tables(0).Compute("sum(Goodsamount)", Filters) Is System.DBNull.Value Then
                                SumCount = 0.0
                            Else
                                SumCount = Convert.ToDouble(DetailDS.Tables(0).Compute("sum(Goodsamount)", Filters))
                            End If
                            If SumCount >= mRow("Goodsamount") Then
                                Continue For
                            End If
                            If Rows.Length > 0 Then
                                Dim ItemNo As String = Rows(0).Item("GoodsBarCode") & ""
                                Dim RowIndex As Integer = 0
                                For j As Integer = 0 To DetailDS.Tables(0).Rows.Count - 1
                                    If DetailDS.Tables(0).Rows(j).Item("GoodsBarCode").ToString.ToLower = ItemNo.ToLower Then
                                        RowIndex = j
                                        Exit For
                                    End If
                                Next
                                If Me.cmbOutStoreType.SelectedIndex = 4 Then
                                    NewRow("ItemNo") = Format(DetailDS.Tables(0).Rows.Count + 1, "000")
                                    NewRow("GoodsBarCode") = mRow("BarCode") & ""
                                    NewRow("GoodsCode") = mRow("Code") & ""
                                    NewRow("SupperItem") = mRow("SupperItem") & ""
                                    NewRow("GoodsName") = mRow("Cnname") & ""
                                    NewRow("GoodsEname") = mRow("Enname") & ""
                                    NewRow("GoodsSpec") = mRow("Spec") & ""
                                    NewRow("Batch") = mRow("batch") & ""
                                    NewRow("storeplace") = mRow("storeplace") & ""
                                    DetailDS.Tables(0).Rows.Add(NewRow)
                                Else
                                    MsgBox("貨品 [" & mRow("BarCode") & "] 已經存在列表中！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                                    Me.DGV_Detail.Focus()
                                    Me.DGV_Detail.CurrentCell = Me.DGV_Detail.Rows(RowIndex).Cells("goodsamount")
                                    Exit Sub
                                End If

                            Else
                                NewRow("ItemNo") = Format(DetailDS.Tables(0).Rows.Count + 1, "000")
                                NewRow("GoodsBarCode") = mRow("BarCode") & ""
                                NewRow("GoodsCode") = mRow("Code") & ""
                                NewRow("SupperItem") = mRow("SupperItem") & ""
                                NewRow("GoodsName") = mRow("Cnname") & ""
                                NewRow("GoodsEname") = mRow("Enname") & ""
                                NewRow("GoodsSpec") = mRow("Spec") & ""
                                NewRow("Batch") = mRow("batch") & ""
                                NewRow("storeplace") = mRow("storeplace") & ""
                                DetailDS.Tables(0).Rows.Add(NewRow)
                            End If
                            Exit For
                        Next
                    End If
                End If
            Next
            DetailDS.AcceptChanges()
            Me.DGV_Detail.DataSource = DetailDS.Tables(0)
            For i As Int16 = 0 To Me.DGV_Detail.Rows.Count - 2
                If Me.DGV_Detail.Rows(i).IsNewRow = False Then
                    If Me.DGV_Detail.Rows(i).Cells("GoodsBarCode").Value Is DBNull.Value Then
                        Me.DGV_Detail.Rows.RemoveAt(i)
                    End If
                End If
            Next
            If DetailDS.Tables(0).Rows.Count > 0 Then
                Me.DGV_Detail.Focus()
                Me.DGV_Detail.CurrentCell = Me.DGV_Detail.Rows(Me.DGV_Detail.CurrentRow.Index).Cells("goodsamount")
            End If
        Catch ex As Exception
            MsgBox("AddDataToGrid:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub ImportAddDataToGrid2(ByVal BarCode As String, ByVal qty As Integer)

        Dim m_Ds As New DataSet
        Try
            Dim Str() As String = BarCode.Split("^")
            Dim WhereStr As String = ""
            Dim Filters As String = ""
            Dim SumCount As Double = 0
            Dim sql As String

            For i As Integer = 0 To Str.Length - 1
                If Str(i).Length > 0 Then
                    If Me.cmbOutStoreType.SelectedIndex = 1 Then
                        'WhereStr = " and isnull(e.fVirtual,'')=1"
                    Else
                        WhereStr = " and isnull(e.fVirtual,'')<>1 and isnull(e.fBuJian,'')<>1"
                    End If
                    sql = "select a.Period,a.StoreHouse,replace(a.Barcode,'*','') as Barcode,a.Batch,a.StorePlace,a.Goodsamount,b.Code,b.SupperItem,b.Enname,b.Cnname,c.ColorSName as Color,d.SizeSName as Spec from "
                    sql += " (select Period,StoreHouse,BarCode,Batch,StorePlace,sum(Goodsamount) as Goodsamount from V_VisualStoreQuery   group by StoreHouse,Period,barcode,Batch,StorePlace) a"
                    sql += " inner join BSC_Goods b on a.BarCode=b.BarCode"
                    sql += " inner join BSC_ColorDefine c on b.Color=c.ColorCode "
                    sql += " inner join BSC_SizeDefine d on b.Spec=d.SizeCode "
                    sql += " left join BSC_Storage e on a.StorePlace=e.fStorageId"
                    sql += " where a.StoreHouse='" & PubCompanyCode & "' and isnull(a.Goodsamount,0.00)>0" & WhereStr & " and isnull(a.BarCode,'')='*" & Str(i) & "*' order by Batch asc,storePlace asc ,Goodsamount asc ;"


                    m_Ds = ReturnDataset(sql)
                    If m_Ds.Tables(0).Rows.Count > 0 Then
                        For Each mRow As DataRow In m_Ds.Tables(0).Rows
                            Dim NewRow As DataRow = DetailDS.Tables(0).NewRow
                            Dim Rows() As DataRow = DetailDS.Tables(0).Select("GoodsBarCode='" & mRow("BarCode") & "' and Batch='" & mRow("batch") & "' and storeplace='" & mRow("storeplace") & "'")
                            Filters = "GoodsBarcode='" & mRow("BarCode") & "' and Batch='" & mRow("batch") & "' and StorePlace='" & mRow("storeplace") & "'"
                            If DetailDS.Tables(0).Compute("sum(Goodsamount)", Filters) Is System.DBNull.Value Then
                                SumCount = 0.0
                            Else
                                SumCount = Convert.ToDouble(DetailDS.Tables(0).Compute("sum(Goodsamount)", Filters))
                            End If
                            If SumCount >= mRow("Goodsamount") Then
                                Continue For
                            End If
                            If Rows.Length > 0 Then
                                Dim ItemNo As String = Rows(0).Item("GoodsBarCode") & ""
                                Dim RowIndex As Integer = 0
                                For j As Integer = 0 To DetailDS.Tables(0).Rows.Count - 1
                                    If DetailDS.Tables(0).Rows(j).Item("GoodsBarCode").ToString.ToLower = ItemNo.ToLower Then
                                        RowIndex = j
                                        Exit For
                                    End If
                                Next
                                If Me.cmbOutStoreType.SelectedIndex = 4 Then

                                    currentBatch = mRow("batch") & ""
                                    currentStoreplace = mRow("storeplace") & ""
                                    currentBarcode = mRow("BarCode") & ""
                                    Dim Rowss() As DataRow = m_Ds.Tables(0).Select("Barcode='" & currentBarcode & "' and batch='" & currentBatch & "' and Storeplace='" & currentStoreplace & "'")
                                    If Rowss.Length > 0 Then
                                        ReadQTY = Rowss(0).Item("Goodsamount")
                                    End If
                                    If qty > ReadQTY Then
                                        NewRow("ItemNo") = Format(DetailDS.Tables(0).Rows.Count + 1, "000")
                                        NewRow("GoodsBarCode") = mRow("BarCode") & ""
                                        NewRow("GoodsCode") = mRow("Code") & ""
                                        NewRow("SupperItem") = mRow("SupperItem") & ""
                                        NewRow("GoodsName") = mRow("Cnname") & ""
                                        NewRow("GoodsEname") = mRow("Enname") & ""
                                        NewRow("GoodsSpec") = mRow("Spec") & ""
                                        NewRow("Batch") = mRow("batch") & ""
                                        NewRow("storeplace") = mRow("storeplace") & ""
                                        NewRow("Goodsamount") = ReadQTY
                                        DetailDS.Tables(0).Rows.Add(NewRow)
                                    Else
                                        NewRow("ItemNo") = Format(DetailDS.Tables(0).Rows.Count + 1, "000")
                                        NewRow("GoodsBarCode") = mRow("BarCode") & ""
                                        NewRow("GoodsCode") = mRow("Code") & ""
                                        NewRow("SupperItem") = mRow("SupperItem") & ""
                                        NewRow("GoodsName") = mRow("Cnname") & ""
                                        NewRow("GoodsEname") = mRow("Enname") & ""
                                        NewRow("GoodsSpec") = mRow("Spec") & ""
                                        NewRow("Batch") = mRow("batch") & ""
                                        NewRow("storeplace") = mRow("storeplace") & ""
                                        NewRow("Goodsamount") = qty
                                        DetailDS.Tables(0).Rows.Add(NewRow)
                                    End If
                                Else
                                    MsgBox("貨品 [" & mRow("BarCode") & "] 已經存在列表中！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                                    Me.DGV_Detail.Focus()
                                    Me.DGV_Detail.CurrentCell = Me.DGV_Detail.Rows(RowIndex).Cells("goodsamount")
                                    Exit Sub
                                End If

                            Else


                                currentBatch = mRow("batch") & ""
                                currentStoreplace = mRow("storeplace") & ""
                                currentBarcode = mRow("BarCode") & ""
                                Dim Rowss() As DataRow = m_Ds.Tables(0).Select("Barcode='" & currentBarcode & "' and batch='" & currentBatch & "' and Storeplace='" & currentStoreplace & "'")
                                If Rowss.Length > 0 Then
                                    ReadQTY = Rowss(0).Item("Goodsamount")
                                End If



                                If qty > ReadQTY Then
                                    NewRow("ItemNo") = Format(DetailDS.Tables(0).Rows.Count + 1, "000")
                                    NewRow("GoodsBarCode") = mRow("BarCode") & ""
                                    NewRow("GoodsCode") = mRow("Code") & ""
                                    NewRow("SupperItem") = mRow("SupperItem") & ""
                                    NewRow("GoodsName") = mRow("Cnname") & ""
                                    NewRow("GoodsEname") = mRow("Enname") & ""
                                    NewRow("GoodsSpec") = mRow("Spec") & ""
                                    NewRow("Batch") = mRow("batch") & ""
                                    NewRow("storeplace") = mRow("storeplace") & ""
                                    NewRow("Goodsamount") = ReadQTY
                                    DetailDS.Tables(0).Rows.Add(NewRow)
                                Else
                                    NewRow("ItemNo") = Format(DetailDS.Tables(0).Rows.Count + 1, "000")
                                    NewRow("GoodsBarCode") = mRow("BarCode") & ""
                                    NewRow("GoodsCode") = mRow("Code") & ""
                                    NewRow("SupperItem") = mRow("SupperItem") & ""
                                    NewRow("GoodsName") = mRow("Cnname") & ""
                                    NewRow("GoodsEname") = mRow("Enname") & ""
                                    NewRow("GoodsSpec") = mRow("Spec") & ""
                                    NewRow("Batch") = mRow("batch") & ""
                                    NewRow("storeplace") = mRow("storeplace") & ""
                                    NewRow("Goodsamount") = qty
                                    DetailDS.Tables(0).Rows.Add(NewRow)
                                End If

                            End If
                            currentBatch = mRow("batch") & ""
                            currentStoreplace = mRow("storeplace") & ""
                            Exit For
                        Next

                    End If
                End If
            Next
            DetailDS.AcceptChanges()
            Me.DGV_Detail.DataSource = DetailDS.Tables(0)
            For i As Int16 = 0 To Me.DGV_Detail.Rows.Count - 2
                If Me.DGV_Detail.Rows(i).IsNewRow = False Then
                    If Me.DGV_Detail.Rows(i).Cells("GoodsBarCode").Value Is DBNull.Value Then
                        Me.DGV_Detail.Rows.RemoveAt(i)
                    End If
                End If
            Next
            If DetailDS.Tables(0).Rows.Count > 0 Then
                Me.DGV_Detail.Focus()
                Me.DGV_Detail.CurrentCell = Me.DGV_Detail.Rows(Me.DGV_Detail.CurrentRow.Index).Cells("goodsamount")
            End If
        Catch ex As Exception
            MsgBox("AddDataToGrid:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub
    Private Sub ImportAddDataToGridIA(ByVal BarCode As String, ByVal qty As Integer, ByVal IANum As String)

        Dim m_Ds As New DataSet
        Try
            Dim Str() As String = BarCode.Split("^")
            Dim WhereStr As String = ""
            Dim Filters As String = ""
            Dim SumCount As Double = 0
            Dim sql As String

            For i As Integer = 0 To Str.Length - 1
                If Str(i).Length > 0 Then
                    If Me.cmbOutStoreType.SelectedIndex = 1 Then

                    Else
                        WhereStr = " and isnull(e.fVirtual,'')<>1 and isnull(e.fBuJian,'')<>1"
                    End If
                    sql = "select a.Period,a.StoreHouse,replace(a.Barcode,'*','') as Barcode,a.Batch,a.StorePlace,a.Goodsamount,b.Code,b.SupperItem,b.Enname,b.Cnname,c.ColorSName as Color,d.SizeSName as Spec from "
                    sql += " (select Period,StoreHouse,BarCode,Batch,StorePlace,sum(Goodsamount) as Goodsamount from V_VisualStoreQuery   group by StoreHouse,Period,barcode,Batch,StorePlace) a"
                    sql += " inner join BSC_Goods b on a.BarCode=b.BarCode"
                    sql += " inner join BSC_ColorDefine c on b.Color=c.ColorCode "
                    sql += " inner join BSC_SizeDefine d on b.Spec=d.SizeCode "
                    sql += " left join BSC_Storage e on a.StorePlace=e.fStorageId"
                    sql += " where a.StoreHouse='" & PubCompanyCode & "' and isnull(a.Goodsamount,0.00)>0" & WhereStr & " and isnull(a.BarCode,'')='*" & Str(i) & "*' order by Batch asc,storePlace asc ,Goodsamount asc ;"


                    m_Ds = ReturnDataset(sql)
                    If m_Ds.Tables(0).Rows.Count > 0 Then
                        For Each mRow As DataRow In m_Ds.Tables(0).Rows
                            Dim NewRow As DataRow = DetailDS.Tables(0).NewRow
                            Dim Rows() As DataRow = DetailDS.Tables(0).Select("GoodsBarCode='" & mRow("BarCode") & "' and Batch='" & mRow("batch") & "' and storeplace='" & mRow("storeplace") & "'")
                            Filters = "GoodsBarcode='" & mRow("BarCode") & "' and Batch='" & mRow("batch") & "' and StorePlace='" & mRow("storeplace") & "'"
                            If DetailDS.Tables(0).Compute("sum(Goodsamount)", Filters) Is System.DBNull.Value Then
                                SumCount = 0.0
                            Else
                                SumCount = Convert.ToDouble(DetailDS.Tables(0).Compute("sum(Goodsamount)", Filters))
                            End If
                            If SumCount >= mRow("Goodsamount") Then
                                Continue For
                            End If
                            If Rows.Length > 0 Then
                                Dim ItemNo As String = Rows(0).Item("GoodsBarCode") & ""
                                Dim RowIndex As Integer = 0
                                For j As Integer = 0 To DetailDS.Tables(0).Rows.Count - 1
                                    If DetailDS.Tables(0).Rows(j).Item("GoodsBarCode").ToString.ToLower = ItemNo.ToLower Then
                                        RowIndex = j
                                        Exit For
                                    End If
                                Next
                                If Me.cmbOutStoreType.SelectedIndex = 4 Then

                                    currentBatch = mRow("batch") & ""
                                    currentStoreplace = mRow("storeplace") & ""
                                    currentBarcode = mRow("BarCode") & ""
                                    Dim Rowss() As DataRow = m_Ds.Tables(0).Select("Barcode='" & currentBarcode & "' and batch='" & currentBatch & "' and Storeplace='" & currentStoreplace & "'")
                                    If Rowss.Length > 0 Then
                                        ReadQTY = Rowss(0).Item("Goodsamount")
                                    End If
                                    If qty > ReadQTY Then
                                        NewRow("ItemNo") = Format(DetailDS.Tables(0).Rows.Count + 1, "000")
                                        NewRow("PoNum") = IANum
                                        NewRow("GoodsBarCode") = mRow("BarCode") & ""
                                        NewRow("GoodsCode") = mRow("Code") & ""
                                        NewRow("SupperItem") = mRow("SupperItem") & ""
                                        NewRow("GoodsName") = mRow("Cnname") & ""
                                        NewRow("GoodsEname") = mRow("Enname") & ""
                                        NewRow("GoodsSpec") = mRow("Spec") & ""
                                        NewRow("Batch") = mRow("batch") & ""
                                        NewRow("storeplace") = mRow("storeplace") & ""
                                        NewRow("Goodsamount") = ReadQTY
                                        DetailDS.Tables(0).Rows.Add(NewRow)
                                    Else
                                        NewRow("ItemNo") = Format(DetailDS.Tables(0).Rows.Count + 1, "000")
                                        NewRow("PoNum") = IANum
                                        NewRow("GoodsBarCode") = mRow("BarCode") & ""
                                        NewRow("GoodsCode") = mRow("Code") & ""
                                        NewRow("SupperItem") = mRow("SupperItem") & ""
                                        NewRow("GoodsName") = mRow("Cnname") & ""
                                        NewRow("GoodsEname") = mRow("Enname") & ""
                                        NewRow("GoodsSpec") = mRow("Spec") & ""
                                        NewRow("Batch") = mRow("batch") & ""
                                        NewRow("storeplace") = mRow("storeplace") & ""
                                        NewRow("Goodsamount") = qty
                                        DetailDS.Tables(0).Rows.Add(NewRow)
                                    End If
                                Else
                                    MsgBox("貨品 [" & mRow("BarCode") & "] 已經存在列表中！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                                    Me.DGV_Detail.Focus()
                                    Me.DGV_Detail.CurrentCell = Me.DGV_Detail.Rows(RowIndex).Cells("goodsamount")
                                    Exit Sub
                                End If

                            Else


                                currentBatch = mRow("batch") & ""
                                currentStoreplace = mRow("storeplace") & ""
                                currentBarcode = mRow("BarCode") & ""
                                Dim Rowss() As DataRow = m_Ds.Tables(0).Select("Barcode='" & currentBarcode & "' and batch='" & currentBatch & "' and Storeplace='" & currentStoreplace & "'")
                                If Rowss.Length > 0 Then
                                    ReadQTY = Rowss(0).Item("Goodsamount")
                                End If



                                If qty > ReadQTY Then
                                    NewRow("ItemNo") = Format(DetailDS.Tables(0).Rows.Count + 1, "000")
                                    NewRow("PoNum") = IANum
                                    NewRow("GoodsBarCode") = mRow("BarCode") & ""
                                    NewRow("GoodsCode") = mRow("Code") & ""
                                    NewRow("SupperItem") = mRow("SupperItem") & ""
                                    NewRow("GoodsName") = mRow("Cnname") & ""
                                    NewRow("GoodsEname") = mRow("Enname") & ""
                                    NewRow("GoodsSpec") = mRow("Spec") & ""
                                    NewRow("Batch") = mRow("batch") & ""
                                    NewRow("storeplace") = mRow("storeplace") & ""
                                    NewRow("Goodsamount") = ReadQTY
                                    DetailDS.Tables(0).Rows.Add(NewRow)
                                Else
                                    NewRow("ItemNo") = Format(DetailDS.Tables(0).Rows.Count + 1, "000")
                                    NewRow("PoNum") = IANum
                                    NewRow("GoodsBarCode") = mRow("BarCode") & ""
                                    NewRow("GoodsCode") = mRow("Code") & ""
                                    NewRow("SupperItem") = mRow("SupperItem") & ""
                                    NewRow("GoodsName") = mRow("Cnname") & ""
                                    NewRow("GoodsEname") = mRow("Enname") & ""
                                    NewRow("GoodsSpec") = mRow("Spec") & ""
                                    NewRow("Batch") = mRow("batch") & ""
                                    NewRow("storeplace") = mRow("storeplace") & ""
                                    NewRow("Goodsamount") = qty
                                    DetailDS.Tables(0).Rows.Add(NewRow)
                                End If

                            End If
                            currentBatch = mRow("batch") & ""
                            currentStoreplace = mRow("storeplace") & ""
                            Exit For
                        Next

                    End If
                End If
            Next
            DetailDS.AcceptChanges()
            Me.DGV_Detail.DataSource = DetailDS.Tables(0)
            For i As Int16 = 0 To Me.DGV_Detail.Rows.Count - 2
                If Me.DGV_Detail.Rows(i).IsNewRow = False Then
                    If Me.DGV_Detail.Rows(i).Cells("GoodsBarCode").Value Is DBNull.Value Then
                        Me.DGV_Detail.Rows.RemoveAt(i)
                    End If
                End If
            Next
            If DetailDS.Tables(0).Rows.Count > 0 Then
                Me.DGV_Detail.Focus()
                Me.DGV_Detail.CurrentCell = Me.DGV_Detail.Rows(Me.DGV_Detail.CurrentRow.Index).Cells("goodsamount")
            End If
        Catch ex As Exception
            MsgBox("AddDataToGrid:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub
    Private Sub LoadGoodsBarCode(ByVal BarCode As String)

        Try
            Dim Str() As String = BarCode.Split("^")
            Dim WhereStr As String = ""
            Dim sql As String

            If Me.cmbOutStoreType.SelectedIndex = 1 Then
                WhereStr = " and isnull(e.fVirtual,'')=1"
            Else
                WhereStr = " and isnull(e.fVirtual,'')<>1 and isnull(e.fBuJian,'')<>1"
            End If
            sql = "select a.Period,a.StoreHouse,replace(a.Barcode,'*','') as Barcode,a.Batch,a.StorePlace,a.Goodsamount,b.Code,b.SupperItem,b.Enname,b.Cnname,c.ColorSName as Color,d.SizeSName as Spec from "
            sql += " (select Period,StoreHouse,BarCode,Batch,StorePlace,sum(Goodsamount) as Goodsamount from V_VisualStoreQuery   group by StoreHouse,Period,barcode,Batch,StorePlace) a"
            sql += " inner join BSC_Goods b on a.BarCode=b.BarCode"
            sql += " inner join BSC_ColorDefine c on b.Color=c.ColorCode "
            sql += " inner join BSC_SizeDefine d on b.Spec=d.SizeCode "
            sql += " left join BSC_Storage e on a.StorePlace=e.fStorageId"
            sql += " where a.StoreHouse='" & PubCompanyCode & "' and isnull(a.Goodsamount,0.00)>0" & WhereStr & " and a.BarCode='*" & Str(0) & "*' order by substring(Batch,4,3),substring(Batch,1,3),Goodsamount"

            StorePlaceDS = New DataSet
            StorePlaceDS = ReturnDataset(sql)
            If StorePlaceDS.Tables(0).Rows.Count > 0 Then
                Me.cmbBatch.DisplayMember = "Batch"
                Me.cmbBatch.ValueMember = "Batch"
                Me.cmbBatch.DataSource = StorePlaceDS.Tables(0)
            End If
        Catch ex As Exception
            MsgBox("LoadGoodsBarCode:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub CreateElement(ByVal ElementNo As String)

        Try

            If ElementDS.Tables(0).Rows.Count > 0 Then

                Dim Rows() As DataRow = ElementDS.Tables(0).Select("Element='" & ElementNo & "'")
                Dim SumElement As Double = 0
                Dim mBool As Boolean = False

                If Rows.Length > 0 Then

                    Dim item As ListViewItem
                    item = New ListViewItem

                    For i As Integer = 0 To Me.lstviewelement.Items.Count - 1

                        SumElement += Convert.ToDouble(Me.lstviewelement.Items(i).SubItems(1).Text)

                        If Me.lstviewelement.Items(i).Tag = item.Tag Then
                            MsgBox("元件號 [" & Me.txtElementNo.Text & "] 已經存在列表中!", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                            Me.txtElementNo.Focus()
                            Exit Sub
                        End If
                    Next

                    item.Tag = txtElementNo.Text.Trim.ToString
                    item.Text = txtElementNo.Text.Trim.ToString

                    If Convert.ToDouble(Me.txtEleOutStoreCount.Text) = SumElement Then
                        MsgBox("出庫數量不能大於元件數量!", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                        Exit Sub
                    ElseIf Convert.ToDouble(Me.txtEleOutStoreCount.Text) < (Convert.ToDouble(Rows(0).Item("Elementamount")) + SumElement) Then
                        MsgBox("元件數量不能大於出庫數量,請分解該元件!", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                        mBool = True
                        Me.txtElementcount.Focus()
                        Exit Sub
                    End If

                    If mBool = False Then
                        item.SubItems.Add(Rows(0).Item("Elementamount"))
                    Else
                        item.SubItems.Add(Me.txtElementcount.Text)
                    End If
                    item.SubItems.Add(Me.combElementunit.Text)
                    item.SubItems.Add(Me.txtEleOutStoreBatch.Text)
                    item.SubItems.Add(Me.txtEleStoreage.Text)
                    item.SubItems.Add(Me.combElementstatus.Text.Split(Space(2))(0))
                    item.Checked = True
                    Me.lstviewelement.Items.Add(item)
                Else
                    MsgBox("該貨品不存在此貨元件號!", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                    Me.txtElementNo.Text = ""
                    Me.txtElementNo.Focus()
                    Exit Sub
                End If

            End If

        Catch ex As Exception
            MsgBox("CreateElement:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub SetForSubreports(ByVal reportDocument As CrystalDecisions.CrystalReports.Engine.ReportDocument, ByVal Ds As DataSet)

        Try
            Dim sections As CrystalDecisions.CrystalReports.Engine.Sections = reportDocument.ReportDefinition.Sections

            For Each mSection As CrystalDecisions.CrystalReports.Engine.Section In sections

                Dim reportObjects As CrystalDecisions.CrystalReports.Engine.ReportObjects = mSection.ReportObjects

                For Each reportObject As CrystalDecisions.CrystalReports.Engine.ReportObject In reportObjects

                    If reportObject.Kind = CrystalDecisions.Shared.ReportObjectKind.SubreportObject Then

                        Dim subreportObject As CrystalDecisions.CrystalReports.Engine.SubreportObject = reportObject

                        Dim subReportDocument As CrystalDecisions.CrystalReports.Engine.ReportDocument = subreportObject.OpenSubreport(subreportObject.SubreportName)

                        If subReportDocument.Name = "Element" Then
                            subReportDocument.SetDataSource(Ds.Tables(1))
                        End If
                    End If


                Next
            Next
        Catch ex As Exception

        End Try

    End Sub

#End Region


#Region "interface"


    Public Function ActionAdd() As Boolean Implements IDServer.IDServer.IDServer.ActionAdd
        If AddEnable = False Then
            MessageBox.Show(My.resources.NotAllowAdd, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
            Exit Function
        End If

        If IsClose = False Then
            MsgBox("當前期別已關賬，不能操作！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
            Exit Function
        End If
        If Me.cmbFromStore.FindString(PubCompanyName) = -1 Then
            MsgBox("對不起，[" & PubCompanyName & "]，設為禁用或未建立資料，不能執行該操作！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
            Exit Function
        End If
        If Me.TabControl1.SelectedIndex = 0 Then
            Me.TabControl1.SelectedIndex = 1
        End If
        ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd
        ClearText()
        SetEnable(True)
        MainForm.BtnEnable(False)
        Me.cmbOutStoreType.Focus()
    End Function

    Public Function ActionCancel() As Boolean Implements IDServer.IDServer.IDServer.ActionCancel

        If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then

            If MsgBox("數據會丟失,確定取消所有嗎?", MsgBoxStyle.Information + MsgBoxStyle.YesNo, Msg.CompanyName) = MsgBoxResult.Yes Then
                ClearText()
                SetEnable(False)
                If Me.TabControl1.SelectedIndex = 0 Then
                ElseIf Me.TabControl1.SelectedIndex = 1 Then
                    If MasterDS.Tables(0).Rows.Count <= 0 Then
                        bFind = False
                    Else
                        FillText(Me.DGV_Master.CurrentRow.Cells("BoNum").Value)
                        bFind = True
                    End If
                End If
                MainForm.BtnEnable(False)
                SetToolEnable()
                'MainForm.ToolStripFilter.Enabled = False
                'MainForm.ToolStripFind.Enabled = False
                'MainForm.ToolStripImport.Enabled = False
                'MainForm.ToolStripDelete.Enabled = False
                'MainForm.ToolStripEdit.Enabled = False
                ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp
            End If

        End If




    End Function

    Public Function ActionDelete() As Boolean Implements IDServer.IDServer.IDServer.ActionDelete

        Try
            If DeleteEnable = False Then
                MessageBox.Show(My.resources.NotAllowdelete, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Exit Function
            End If

            Dim BoNum As String = Me.DGV_Master.CurrentRow.Cells("BoNum").Value
            If BoNum.Length > 0 Then
                If MsgBox(My.Resources.ConfirmDelete, MsgBoxStyle.Question + MsgBoxStyle.OkCancel, Msg.CompanyName) = MsgBoxResult.Ok Then
                    If DeleteDataset(BoNum) = True Then
                        If Me.DGV_Master.Rows.Count > 0 Then
                            FillText(Me.DGV_Master.CurrentRow.Cells("BoNum").Value)
                            SetGridRowBackColor(Me.DGV_Master, MasterDS)
                            MsgBox(My.Resources.DeleteSuccess, MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                        End If
                    End If
                End If
            End If
        Catch ex As Exception
            MsgBox("ActionDelete:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Function

    Public Function ActionEdit() As Boolean Implements IDServer.IDServer.IDServer.ActionEdit
        Try
            If EditEnable = False Then
                MessageBox.Show(My.Resources.NotAllowEidt, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Exit Function
            End If

            If IsClose = False Then
                MsgBox("當前期別已關賬，不能操作！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                Exit Function
            End If
            If Me.cmbFromStore.FindString(PubCompanyName) = -1 Then
                MsgBox("對不起，[" & PubCompanyName & "]，設為禁用或未建立資料，不能執行該操作！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                Exit Function
            End If
            If Me.TabControl1.SelectedIndex = 0 Or Me.TabControl1.SelectedIndex = 1 Then
                Me.TabControl1.SelectedIndex = 1
            End If
            ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit
            SetEnable(True)
            MainForm.BtnEnable(False)
            With MainForm
                .ToolStripFilter.Enabled = False
                .ToolStripImport.Enabled = False
                .ToolStripPrint.Enabled = False
                .ToolStripExport.Enabled = False
                .ToolStripFind.Enabled = False
                .ToolStripFirst.Enabled = False
                .ToolStripNext.Enabled = False
                .ToolStripLast.Enabled = False
                .ToolStripPrivous.Enabled = False
            End With
        Catch ex As Exception
            MsgBox("ActionEdit:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Function

    Public Function ActionExport() As Boolean Implements IDServer.IDServer.IDServer.ActionExport
        If Me.TabControl1.SelectedIndex = 0 Then
            ExportToExcel(Me.DGV_Master, PubCompanyName)
        ElseIf Me.TabControl1.SelectedIndex = 1 Then
            PrintOutStoreNumDetail(Me.DGV_Detail, Me.LabInfo.Text, Me.cmbOutStoreType.Text, Me.cmbToStore1.Text, Me.cmbFromStore.Text, Me.LabOperateDate.Text, Me.txtDeliverCar.Text, Me.txtDeliverPerson.Text, Me.DateTimePicker2.Value, "", 0)
        End If
    End Function

    Public Function ActionFilter() As Boolean Implements IDServer.IDServer.IDServer.ActionFilter
        Try
            Dim Frm_Filter As New Frm_Filter
            Me.Cursor = Cursors.WaitCursor
            Frm_Filter.LoadHeaderCaption(Fields, "Frm_INToutofstrorage")
            Frm_Filter.ShowDialog()
            Me.Cursor = Cursors.Default
            ReBindGridCaption(Me.DGV_Master, "Frm_INToutofstrorage")
        Catch ex As Exception
            MsgBox("ActionFilter:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Function

    Public Function ActionGoFirst() As Boolean Implements IDServer.IDServer.IDServer.ActionGoFirst

    End Function

    Public Function ActionGoLast() As Boolean Implements IDServer.IDServer.IDServer.ActionGoLast

    End Function

    Public Function ActionGoNext() As Boolean Implements IDServer.IDServer.IDServer.ActionGoNext

    End Function

    Public Function ActionGoPrevious() As Boolean Implements IDServer.IDServer.IDServer.ActionGoPrevious

    End Function

    Public Function ActionImport() As Boolean Implements IDServer.IDServer.IDServer.ActionImport

        Try
            Select Case Me.cmbOutStoreType.SelectedIndex
                Case 0
                Case 1
                Case 2
                Case 3
                Case 4
                    ExportDeliverNo(Me.cmbOutStoreType.SelectedIndex)
                Case 5
            End Select

        Catch ex As Exception
            MsgBox("ActionImport:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Function

    Public Function ActionInitialize() As Boolean Implements IDServer.IDServer.IDServer.ActionInitialize

        Try
            If Me.TabControl1.SelectedIndex = 2 Then

                If getstorehousestatus(Me.cmbToStore1.SelectedValue.ToString) = False Then
                Else
                    MsgBox("倉庫不可用，可能目前倉庫設置停用，或者當前倉庫已經過賬！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                    Return False
                End If

            ElseIf Me.TabControl1.SelectedIndex = 1 Then
                If Me.cmbOutStoreType.Text.Length <= 0 Then
                    MsgBox("出庫類型不能為空！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                    Me.cmbOutStoreType.Focus()
                    SendKeys.Send("{F4}")
                    Return False
                End If
                If Me.cmbFromStore.Text.Length <= 0 Then
                    MsgBox("源倉庫不能為空！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                    Me.cmbFromStore.Focus()
                    SendKeys.Send("{F4}")
                    Return False
                Else
                    Dim Rows() As DataRow = StoreDS.Tables(2).Select("fCode='" & Me.cmbFromStore.SelectedValue.ToString & "'")
                    Dim IsStorePlace As Boolean = False
                    If Rows.Length > 0 Then
                        IsStorePlace = Rows(0).Item("fStatus")
                    End If
                    If IsStorePlace = True Then
                        MsgBox("倉庫不可用，可能目前倉庫設置停用，或者當前倉庫已經過賬！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                        Me.cmbFromStore.Focus()
                        SendKeys.Send("{F4}")
                        Return False
                    End If
                End If
                Dim Period As String = Me.DateTimePicker2.Value.Year.ToString & Format(Me.DateTimePicker2.Value.Month, "00")
                Dim GetCurrentDate As String = Me.DateTimePicker2.Value.Year.ToString & "-" & Format(Me.DateTimePicker2.Value.Month, "00") & "-" & Format(Me.DateTimePicker2.Value.Day, "00")
                If PeriodData > Period Then
                    MsgBox("送貨日期必須和當前期別一至！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                    Me.DateTimePicker2.Focus()
                    SendKeys.Send("{F4}")
                    Return False
                End If

                If Me.cmbOutStoreType.SelectedIndex = 2 Then
                    If Me.cmbToStore1.Text.Length <= 0 Then
                        MsgBox("目的倉庫不能為空！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                        Me.cmbToStore1.Focus()
                        SendKeys.Send("{F4}")
                        Return False
                    Else
                        Dim Rows() As DataRow = StoreDS.Tables(3).Select("fCode='" & Me.cmbFromStore.SelectedValue.ToString & "'")
                        Dim IsStorePlace As Boolean = False
                        If Rows.Length > 0 Then
                            IsStorePlace = Rows(0).Item("fStatus")
                        End If
                        If IsStorePlace = True Then
                            MsgBox("倉庫不可用，可能目前倉庫設置停用，或者當前倉庫已經過賬！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                            Me.cmbToStore1.Focus()
                            SendKeys.Send("{F4}")
                            Return False
                        End If
                    End If
                End If

                Dim mTable As DataTable = CType(Me.DGV_Detail.DataSource, DataTable)
                If mTable.Rows.Count <= 0 Then
                    MsgBox("出庫貨品不能為空！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                    Exit Function
                End If
                If mTable.Rows.Count > 0 Then
                    For i As Integer = 0 To mTable.Rows.Count - 1
                        If mTable.Rows(i).Item("goodsamount") Is DBNull.Value Or mTable.Rows(i).Item("goodsamount") & "" = "" Then
                            MsgBox("第 [" & i + 1 & "] 行，數量列不能為空！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                            Me.DGV_Detail.Focus()
                            Me.DGV_Detail.CurrentCell = Me.DGV_Detail.Rows(i).Cells("goodsamount")
                            Return False
                        End If
                    Next
                End If
                'Dim StorePlace As String = ""
                'Dim sql As String
                'Dim m_Ds As New DataSet
                'sql = "select  * from dbo.BSC_Storage where isnull(fVirtual,'')=1"
                'm_Ds = ReturnDataset(sql)
                'If m_Ds.Tables(0).Rows.Count > 0 Then
                '    StorePlace = m_Ds.Tables(0).Rows(0).Item("fStorageId") & ""
                '    Dim Rows() As DataRow = DetailDS.Tables(0).Select("storeplace='" & StorePlace & "'")
                '    If Rows.Length > 0 Then
                '        If Me.cmbOutStoreType.SelectedIndex <> 1 Then
                '            MsgBox("出庫類型與所出的倉位不一至，請重新選擇出庫類型！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                '            Me.cmbOutStoreType.Focus()
                '            SendKeys.Send("{F4}")
                '            Return False
                '        End If
                '    End If
                'End If
            End If
            Return True

        Catch ex As Exception
            Throw ex
        End Try

    End Function

    Public Function ActionPrint() As Boolean Implements IDServer.IDServer.IDServer.ActionPrint

        Dim mDs As DataSet
        Try
            Me.Cursor = Cursors.WaitCursor

            If Me.DGV_Master.Rows.Count <= 0 Then
                MsgBox("對不起，沒有數據可列印！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                Exit Function
            End If
            Dim Pathstr As String = ""
            Dim sql As String = ""
            Dim ConfigNode() As String = ReadConfigFile.Split(";")
            Dim mServer As String = ""
            Dim mDataBase As String = ""
            Dim mUserID As String = ""
            Dim mPassword As String = ""
            Dim BoNum As String = ""

            Pathstr = GetReportPath("Store", "OutStoreReport.rpt")
            'Pathstr = "D:\Reports\Store\OutStoreReport.rpt"
            For i As Integer = 0 To ConfigNode.Length - 1
                If ConfigNode(i).Split("=")(0).ToLower = "Server".ToLower Then
                    mServer = ConfigNode(i).Split("=")(1)
                End If
                If ConfigNode(i).Split("=")(0).ToLower = "DataBase".ToLower Then
                    mDataBase = ConfigNode(i).Split("=")(1)
                End If
                If ConfigNode(i).Split("=")(0).ToLower = "Uid".ToLower Then
                    mUserID = ConfigNode(i).Split("=")(1)
                End If
                If ConfigNode(i).Split("=")(0).ToLower = "Pwd".ToLower Then
                    mPassword = ConfigNode(i).Split("=")(1)
                End If
            Next

            Dim myReportDoc As New CrystalDecisions.CrystalReports.Engine.ReportDocument
            Dim myParameterValues As New CrystalDecisions.Shared.ParameterValues
            Dim myDiscreteValue As New CrystalDecisions.Shared.ParameterDiscreteValue

            Dim logonInfo As New CrystalDecisions.Shared.TableLogOnInfo
            Dim table As CrystalDecisions.CrystalReports.Engine.Table
            myReportDoc.Load(Pathstr)

            For Each table In myReportDoc.Database.Tables
                logonInfo = table.LogOnInfo
                With logonInfo.ConnectionInfo
                    .ServerName = mServer
                    .DatabaseName = mDataBase
                    .UserID = mUserID
                    .Password = mPassword
                End With
                table.ApplyLogOnInfo(logonInfo)
            Next

            If Me.DGV_Master.SelectedRows.Count > 0 Then
                For i As Integer = 0 To Me.DGV_Master.SelectedRows.Count - 1
                    BoNum += "''" & Me.DGV_Master.SelectedRows(i).Cells("BoNum").Value & "'',"
                Next
                BoNum = BoNum.Remove(BoNum.Length - 1, 1)
            End If
            sql += "Exec Proc_ElementOutStore '" & BoNum & "';"
            mDs = New DataSet
            mDs = ReturnDataset(sql)

            myReportDoc.SetDataSource(mDs.Tables(0))

            My.Forms.Frm_Report.CrystalReportViewer1.ReportSource = myReportDoc
            My.Forms.Frm_Report.CrystalReportViewer1.Zoom(1)
            My.Forms.Frm_Report.CrystalReportViewer1.DisplayGroupTree = False

            Frm_Report.ShowDialog()
            Me.Cursor = Cursors.Default
        Catch ex As Exception
            Me.Cursor = Cursors.Default
            MsgBox("對不起，打印出錯！" & ex.Message & ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Function

    Public Function ActionSave() As Boolean Implements IDServer.IDServer.IDServer.ActionSave
        BtnActionSave()
    End Function

    Public Function ActionSelect() As Boolean Implements IDServer.IDServer.IDServer.ActionSelect

    End Function

    Public Function ActionChecked() As Boolean
        Dim sql As String
        Try
            If CheckEnable = False Then
                MessageBox.Show("對不起，您沒有審核權限", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Exit Function
            End If

            Dim BoNum As String = Me.DGV_Master.CurrentRow.Cells("BoNum").Value
            If BoNum.Length <= 0 Then Exit Function
            Dim CheckDate As String = ServerDate
            If MsgBox("確認審核此單嗎？", MsgBoxStyle.Information + MsgBoxStyle.OkCancel, Msg.CompanyName) = MsgBoxResult.Ok Then
                sql = " UpDate Stor_TradeMaster Set BoStatus='B',CheckPerson='" & PubUserName & "',CheckDate='" & CheckDate & "',CheckComputer='" & My.Computer.Name & "' where BoNum='" & BoNum & "'"
                sql += " UPDATE SAL_IAA SET STATUS ='F' WHERE VOUCHER_NO IN "
                sql += "  (SELECT A.PONUM FROM STOR_TRADEDETAIL A LEFT JOIN STOR_TRADEMASTER B ON A.BONUM = B.BONUM WHERE A.BONUM = '" & BoNum & "' AND INOROUTTYPE ='03')"
                ReturnObject(sql)
                Dim Rows() As DataRow = MasterDS.Tables(0).Select("BoNum='" & BoNum & "'")
                If Rows.Length > 0 Then
                    Rows(0).Item("BoStatus") = "核准"
                    Rows(0).Item("CheckPerson") = PubUserName
                    Rows(0).Item("CheckDate") = CheckDate
                End If
                MasterDS.AcceptChanges()
                Me.DGV_Master.DataSource = MasterDS.Tables(0)
                SetGridRowBackColor(Me.DGV_Master, MasterDS)
                MsgBox("謝謝,核准成功!", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
            End If
        Catch ex As Exception
            MsgBox("ActionChecked:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Function

    Public Function ActionUnchecked() As Boolean
        Dim sql As String
        Try
            If UncheckEnable = False Then
                MessageBox.Show("對不起，您沒有反審核權限", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Exit Function
            End If

            Dim BoNum As String = Me.DGV_Master.CurrentRow.Cells("BoNum").Value
            Dim CheckDate As String = ServerDate
            If BoNum.Length <= 0 Then Exit Function
            If MsgBox("確認反審核此單嗎？", MsgBoxStyle.Information + MsgBoxStyle.OkCancel, Msg.CompanyName) = MsgBoxResult.Ok Then
                sql = "UpDate Stor_TradeMaster Set BoStatus='C',UnCheckPerson='" & PubUserName & "',UnCheckDate='" & CheckDate & "',UnCheckComputer='" & My.Computer.Name & "' where BoNum='" & BoNum & "'"
                sql += " UPDATE SAL_IAA SET STATUS ='B' WHERE VOUCHER_NO IN "
                sql += "  (SELECT A.PONUM FROM STOR_TRADEDETAIL A LEFT JOIN STOR_TRADEMASTER B ON A.BONUM = B.BONUM WHERE A.BONUM = '" & BoNum & "' AND INOROUTTYPE ='03')"
                ReturnObject(sql)
                Dim Rows() As DataRow = MasterDS.Tables(0).Select("BoNum='" & BoNum & "'")
                If Rows.Length > 0 Then
                    Rows(0).Item("BoStatus") = "反核准"
                    Rows(0).Item("CheckPerson") = PubUserName
                    Rows(0).Item("CheckDate") = CheckDate
                End If
                MasterDS.AcceptChanges()
                Me.DGV_Master.DataSource = MasterDS.Tables(0)
                SetGridRowBackColor(Me.DGV_Master, MasterDS)
                MsgBox("謝謝,反核准成功!", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
            End If

        Catch ex As Exception
            MsgBox("ActionUnchecked:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Function

    Public Function ActionComplete() As Boolean
        Try

        Catch ex As Exception
            MsgBox("ActionComplete:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Function

#End Region


#Region "Control Events"


    Private Sub TabControl1_Selected(ByVal sender As Object, ByVal e As System.Windows.Forms.TabControlEventArgs) Handles TabControl1.Selected
        Try
            If Not Me.TabControl1.SelectedTab Is Nothing Then
                Select Case Me.TabControl1.SelectedIndex
                    Case 0
                        IsFilter = True
                        IsExport = True
                        MainForm.ToolStripFind.Enabled = True
                        MainForm.ToolStripFilter.Enabled = True
                        MainForm.ToolStripImport.Enabled = False
                    Case 1
                        If MasterDS.Tables(0).Rows.Count <= 0 Then
                            ClearText()
                        Else
                            Dim fCode As String = Me.DGV_Master.CurrentRow.Cells("BoNum").Value
                            If fCode.Length > 0 Then
                                FillText(fCode)
                            End If
                        End If
                        MainForm.ToolStripFind.Enabled = False
                        MainForm.ToolStripFilter.Enabled = False
                        MainForm.ToolStripImport.Enabled = False
                    Case 2
                        If Me.DGV_Detail.Rows.Count > 0 Then
                            Dim Barcode As String = Me.DGV_Detail.CurrentRow.Cells("GoodsBarCode").Value
                            FillElement(Barcode)
                        End If
                End Select

            End If
        Catch ex As Exception
            MsgBox("TabControl1_Selected:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub TabControl1_Selecting(ByVal sender As Object, ByVal e As System.Windows.Forms.TabControlCancelEventArgs) Handles TabControl1.Selecting
        Try
            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
                e.Cancel = True
            End If
        Catch ex As Exception
            MsgBox("TabControl1_Selecting:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub txtbatch_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Try
            'If Me.txtbarcode.Text.Length <= 0 Then Exit Sub
            Dim StoreHouse As String
            Dim status As String
            'If Me.cmbFromStore1.Text.Length > 0 Then
            '    StoreHouse = Me.cmbFromStore1.SelectedItem.ToString.Split(Space(5))(0)
            'Else
            '    StoreHouse = ""
            'End If
            'If Me.cmboutstatus.Text.Length > 0 Then
            '    status = Me.cmboutstatus.SelectedItem.ToString.Split(Space(5))(0)
            'Else
            '    status = ""
            'End If

            'strsql = "select * from BSC_goods where Barcode='*" + txtbarcode.Text.Trim + "*' ;"
            'strsql += "select a.*,b.tostore  from  Stor_element a, stor_trademaster b  where a.bonuma=b.bonum and  a.elementIsOut=0 and goodsBarcode='*" + txtbarcode.Text.Trim + "*' and   a.elementstatus ='" + status + "'  and  a.bonuma=b.bonum  and elementbatch='" + Cmbgoodsbatch.Text + "'order by element "
            'dsbarcode = New DataSet
            'dsbarcode = ReturnDataset(strsql)

            'If dsbarcode.Tables(0).Rows.Count <= 0 Then
            '    'txtbarcode.Text = ""
            '    'txtbarcode.Focus()
            'End If
            'For Each drow As DataRow In dsbarcode.Tables(0).Rows
            '    'txtcode.Text = drow("code")
            '    'txtcolor.Text = drow("color")
            '    'txtsize.Text = drow("spec")
            '    'txtunit.Text = drow("unit")
            '    B = drow("Iselement")
            '    btnelement.Visible = B
            '    lstviewelement.Visible = B
            'Next
            'If lstviewelement.Visible = True Then
            '    If dsbarcode.Tables(1).Rows.Count > 0 Then
            '        For Each drowelement As DataRow In dsbarcode.Tables(1).Rows
            '            Dim item As New ListViewItem
            '            item.Text = drowelement("element")
            '            Me.lstviewelement.Items.Add(item)
            '            item.SubItems.Add(drowelement("elementamount"))
            '            item.SubItems.Add(drowelement("elementunit"))
            '            item.SubItems.Add(drowelement("elementbatch"))
            '            item.SubItems.Add(drowelement("storeplace"))
            '            item.SubItems.Add(drowelement("elementstatus"))
            '        Next
            '    End If
            'End If
        Catch ex As Exception
            MsgBox("viewgood:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub BtnFind_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnFind.Click
        Try
            Dim sql As String
            Dim whereCondition As String = ""

            If Me.BoNum.Text.Length > 0 Then
                whereCondition = " and a.BoNum like '%" & Me.BoNum.Text & "%'"
            End If

            If Me.cbStartDate1.Checked = True And Me.cbEndDate1.Checked = False Then
                whereCondition += " and Convert(varchar(10),a.OperateDate,21)='" & Format(Me.StartDate1.Value, "yyyy-MM-dd") & "'"
            ElseIf Me.cbStartDate1.Checked = False And Me.cbEndDate1.Checked = True Then
                whereCondition += " and Convert(varchar(10),a.OperateDate,21)='" & Format(Me.EndDate1.Value, "yyyy-MM-dd") & "'"
            ElseIf Me.cbStartDate1.Checked = True And Me.cbEndDate1.Checked = True Then
                whereCondition += " and Convert(varchar(10),a.OperateDate,21) between '" & Format(Me.StartDate1.Value, "yyyy-MM-dd") & "' and '" & Format(Me.EndDate1.Value, "yyyy-MM-dd") & "'"
            End If

            If Me.DeliverNo.Text.Length > 0 Then
                whereCondition += " and a.DeliverNo='" & Me.DeliverNo.Text & "'"
            End If

            If Me.cbStartDate2.Checked = True And Me.cbEndDate2.Checked = False Then
                whereCondition += " and a.DeliverDate='" & Format(Me.StartDate3.Value, "yyyy-MM-dd") & "'"
            ElseIf Me.cbStartDate2.Checked = False And Me.cbEndDate2.Checked = True Then
                whereCondition += " and a.DeliverDate='" & Format(Me.EndDate3.Value, "yyyy-MM-dd") & "'"
            ElseIf Me.cbStartDate2.Checked = True And Me.cbEndDate2.Checked = True Then
                whereCondition += " and a.DeliverDate between '" & Format(Me.StartDate3.Value, "yyyy-MM-dd") & "' and '" & Format(Me.EndDate3.Value, "yyyy-MM-dd") & "'"
            End If

            If Me.txtfBatch.Text.Length > 0 Then
                whereCondition += " and g.Batch='" & Me.txtfBatch.Text & "'"
            End If

            If Me.cmbquerystore.Text.Length > 0 Then
                whereCondition += " and a.FromStore='" & Me.cmbquerystore.SelectedValue.ToString & "'"
            End If

            If Me.cmbqueryoperationtype.Text.Length > 0 Then
                whereCondition += " and a.InOrOutType='" & Me.cmbqueryoperationtype.SelectedValue.ToString & "'"
            End If

            If Me.cmbOrdeStatus.Text.Length > 0 Then
                whereCondition += " and BoStatus='" & Me.cmbOrdeStatus.SelectedValue.ToString & "'"
            End If

            If Me.cmbOperatePerson.Text.Length > 0 Then
                whereCondition += " and OperatePerson='" & Me.cmbOperatePerson.SelectedValue.ToString & "'"
            End If

            sql = "select distinct a.BoNum,b.TradeType,c.InOrOutType,d.ToStore,e.FromStore,a.StorePlace,a.DeliverNo,a.DeliverPerson,a.DeliverDate,a.DeliverCar,BoStatus=f.ListA,"
            sql += "a.Remark,a.OperatePerson,a.OperateDate,a.CheckPerson,a.CheckDate  from Stor_TradeMaster a left join "
            sql += " (select a.BoNum,b.name as TradeType from Stor_TradeMaster a inner join Stor_tradecode b on a.TradeType=b.AddorNot where b.code='02') b on a.BoNum=b.BoNum left join "
            sql += " (select a.BoNum,b.ListA as InOrOutType from Stor_TradeMaster a inner join BSC_OtherDefineB b on a.InOrOutType=b.ListCode where b.ItemNo=58) c on a.BoNum=c.BoNum left join "
            sql += " (select a.BoNum,b.fShortName as ToStore from Stor_TradeMaster a inner join BSC_StoreHouse b on a.ToStore=b.fCode) d on a.BoNum=d.boNum left join "
            sql += " (select a.BoNum,b.fShortName as FromStore from Stor_TradeMaster a inner join BSC_StoreHouse b on a.FromStore=b.fCode) e on a.BoNum=e.BoNum inner join BSC_OtherDefineB f on a.BoStatus=f.ListCode"
            sql += " inner join Stor_TradeDetail g on a.bonum = g.bonum "
            sql += " where f.ItemNo=16 and a.TradeType='-'" & whereCondition

            MasterDS = ReturnDataset(sql)
            Me.DGV_Master.DataSource = MasterDS.Tables(0)
            bFind = MasterDS.Tables(0).Rows.Count > 0
            ''SetGridRowBackColor(Me.DGV_Master, MasterDS)
            SetToolEnable()
        Catch ex As Exception
            MsgBox("BtnActionFind:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
        SetToolEnable()
    End Sub

    Private Sub SetGridRowBackColor(ByVal Grid As DataGridView, ByVal DS As DataSet)
        Try
            If DS.Tables(0).Rows.Count <= 0 Then Exit Sub

            For i As Integer = 0 To DS.Tables(0).Rows.Count - 1
                If DS.Tables(0).Rows(i).Item("BoStatus").ToString = "核准" Then
                    Grid.Rows(i).DefaultCellStyle.BackColor = System.Drawing.SystemColors.Info
                ElseIf DS.Tables(0).Rows(i).Item("BoStatus").ToString = "反核准" Then
                    Grid.Rows(i).DefaultCellStyle.BackColor = Color.DeepSkyBlue
                ElseIf DS.Tables(0).Rows(i).Item("BoStatus").ToString = "保存" Then
                    Grid.Rows(i).DefaultCellStyle.BackColor = Color.AliceBlue
                ElseIf DS.Tables(0).Rows(i).Item("BoStatus").ToString = "結案" Then
                    Grid.Rows(i).DefaultCellStyle.BackColor = Color.Gainsboro
                End If
            Next
        Catch ex As Exception
            MsgBox("SetGridRowBackColor:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub rb1_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs)

        If Me.TabControl1.SelectedIndex = 1 Then
            Dim sql As String = ""
            Dim FromStore As String = Me.cmbFromStore.SelectedValue.ToString
            Dim m_DS As New DataSet
            sql = "select distinct(Replace(b.GoodsBarcode,'*','')) as GoodsBarCode from Stor_TradeMaster a inner join Stor_TradeDetail b on a.bonum=b.bonum where a.TradeType='+' and a.ToStore='" & FromStore & "'"

            m_DS = ReturnDataset(sql)
            Me.cmbGoodsBarcode.Text = ""
            Me.cmbGoodsBarcode.DisplayMember = "GoodsBarcode"
            Me.cmbGoodsBarcode.ValueMember = "GoodsBarCode"
            Me.cmbGoodsBarcode.DataSource = m_DS.Tables(0)
            Dim Rows() As DataRow = StoreDS.Tables(2).Select("fCode='" & FromStore & "'")
            If Rows.Length > 0 Then
                IsPlace = Rows(0).Item("fStorePlace")
            End If
            If IsPlace = True Then

            Else
                Me.cmbStorePlace.Enabled = False
            End If
        End If

    End Sub

    Private Sub cmbOutStoreType_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmbOutStoreType.SelectedIndexChanged

        If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
            If Me.cmbOutStoreType.SelectedIndex = 2 Then
                Me.cmbToStore1.Enabled = True
                Me.txtSaleOrdeNo.Enabled = False
                MainForm.ToolStripImport.Enabled = False
                Me.DGV_Detail.Columns("PoNum").Visible = True
                ' Me.DGV_Detail.Columns("PoNumItem").Visible = True
                Me.DGV_Sum.Columns("PoNum").Visible = True
                ' Me.DGV_Sum.Columns("PoNumItem").Visible = True
            ElseIf Me.cmbOutStoreType.SelectedIndex = 4 Then
                Me.cmbToStore1.Enabled = False
                Me.txtSaleOrdeNo.Enabled = False
                MainForm.ToolStripImport.Enabled = True
                Me.DGV_Detail.Columns("PoNum").Visible = True
                Me.DGV_Detail.Columns("PoNumItem").Visible = True
                Me.DGV_Sum.Columns("PoNum").Visible = True
                Me.DGV_Sum.Columns("PoNumItem").Visible = True
            Else
                Me.cmbToStore1.Enabled = False
                Me.txtSaleOrdeNo.Enabled = False
                MainForm.ToolStripImport.Enabled = False
                Me.DGV_Detail.Columns("PoNum").Visible = False
                Me.DGV_Detail.Columns("PoNumItem").Visible = False
                Me.DGV_Sum.Columns("PoNum").Visible = False
                Me.DGV_Sum.Columns("PoNumItem").Visible = False
            End If
        End If
    End Sub

    Private Sub cmboperationtype_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
        If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
            'If Me.cmboperationtype.SelectedIndex = 2 Then
            '    Me.cmbToStore.Enabled = True
            'Else
            '    Me.cmbToStore.Enabled = False
            'End If
        End If
    End Sub

    Private Sub DateTimePicker1_ValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DateTimePicker2.ValueChanged
        If sender.name.ToString.ToLower = "DateTimePicker1".ToLower Then
        ElseIf sender.name.ToString.ToLower = "DateTimePicker2".ToLower Then
        End If
    End Sub

    Private Sub GoodsCount_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles GoodsCount.KeyDown
        Try

            If e.KeyCode = Keys.Enter Then
                Dim Batch As String = Me.cmbBatch.SelectedValue.ToString
                Dim StorePlace As String = Me.cmbStorePlace.Text
                Dim Filter As String = "GoodsBarcode='" & Me.cmbGoodsBarcode.Text & "' and Batch='" & Me.cmbBatch.SelectedValue.ToString & "' and StorePlace='" & Me.cmbStorePlace.Text & "'"
                Dim Goodsamount As Double = 0
                Dim SumCount As Double = 0

                If Not Double.TryParse(Me.GoodsCount.Text, Goodsamount) Then
                    MsgBox("無效的輸入或格式不正確！", MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
                    Me.GoodsCount.Focus()
                    Me.GoodsCount.SelectAll()
                    Exit Sub
                End If
                If DetailDS.Tables(0).Compute("sum(Goodsamount)", Filter) Is System.DBNull.Value Then
                    SumCount = 0.0
                Else
                    SumCount = Convert.ToDouble(DetailDS.Tables(0).Compute("sum(Goodsamount)", Filter))
                End If

                Dim Rows() As DataRow = StorePlaceDS.Tables(0).Select("Batch='" & Batch & "' and StorePlace='" & StorePlace & "'")
                If Rows.Length > 0 Then
                    Dim NewRow As DataRow = DetailDS.Tables(0).NewRow
                    Goodsamount = Convert.ToDouble(Rows(0)("Goodsamount"))
                    If (SumCount + Convert.ToDouble(Me.GoodsCount.Text)) > Goodsamount Then
                        MsgBox("對不起，該貨品庫存不足，請及時補充庫存！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                        Exit Sub
                    Else
                        For Each mRow As DataRow In Rows
                            NewRow("ItemNo") = Format(DetailDS.Tables(0).Rows.Count + 1, "000")
                            NewRow("GoodsBarCode") = mRow("BarCode") & ""
                            NewRow("GoodsCode") = mRow("Code") & ""
                            NewRow("SupperItem") = mRow("SupperItem") & ""
                            NewRow("GoodsName") = mRow("Cnname") & ""
                            NewRow("GoodsColor") = mRow("Color") & ""
                            NewRow("GoodsSpec") = mRow("Spec") & ""
                            NewRow("Goodsamount") = Me.GoodsCount.Text
                            NewRow("Batch") = mRow("batch") & ""
                            NewRow("storeplace") = mRow("storeplace") & ""
                            DetailDS.Tables(0).Rows.Add(NewRow)
                        Next
                    End If
                Else
                    MsgBox("對不起，該貨品庫存不足，請及時補充庫存！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                    Exit Sub
                End If
            End If

        Catch ex As Exception
            MsgBox("GoodsCount_KeyDown:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub GoodsCount_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles GoodsCount.KeyPress

        Try

            If Not Char.IsControl(e.KeyChar) And Not Char.IsNumber(e.KeyChar) And Not Char.IsPunctuation(e.KeyChar) Then
                e.Handled = True
            ElseIf Char.IsPunctuation(e.KeyChar) Then
                If e.KeyChar = "." Then
                    If Me.GoodsCount.Text.LastIndexOf(".") <> -1 Then
                        e.Handled = True
                    End If
                Else
                    e.Handled = True
                End If
            End If
        Catch ex As Exception
            MsgBox("GoodsCount_KeyPress:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub DGV_Detail_CellDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DGV_Detail.CellDoubleClick
        Try
            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
                If e.ColumnIndex = 4 Then
                    Dim Frm_SelectGoods As New Frm_SelectGoods
                    If Me.cmbOutStoreType.SelectedIndex = 1 Then
                        Frm_SelectGoods.Index = 3
                    Else
                        Frm_SelectGoods.Index = 1
                    End If
                    Frm_SelectGoods.ShowDialog()
                    If Frm_SelectGoods.BarCode Is Nothing Then
                        Exit Sub
                    End If
                    Dim BarCode As String = Frm_SelectGoods.BarCode
                    If BarCode = "" Or BarCode.Length <= 0 Then
                        Exit Sub
                    End If
                    AddDataToGrid(BarCode)
                End If
            End If
        Catch ex As Exception
            MsgBox("DGV_Detail_CellDoubleClick:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub DGV_Detail_CellValidated(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DGV_Detail.CellValidated
        Me.DGV_Detail.Rows(e.RowIndex).ErrorText = Nothing
    End Sub

    Private Sub DGV_Detail_CellValidating(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellValidatingEventArgs) Handles DGV_Detail.CellValidating
        Try
            If e.ColumnIndex = 9 Then
                Dim testInteger As Double
                Me.DGV_Detail.ShowCellErrors = True
                Me.DGV_Detail.ShowRowErrors = True
                If Me.DGV_Detail.CurrentRow.IsNewRow Then
                    Exit Sub
                End If
                If Not e.FormattedValue.ToString.Length = 0 Then
                    If Not Double.TryParse(e.FormattedValue.ToString, testInteger) Then
                        e.Cancel = True
                    End If
                End If
            End If
        Catch ex As Exception
            MsgBox("DGV_Detail_CellValidating:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub
    Private Sub AutoAddNewRow(ByVal CurrentBarcode As String, ByVal CurrentBatch As String, ByVal CurrentStoreplace As String, ByVal CurrentGoodsamount As Integer)
        If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then

            Dim sql As String
            Dim m_Ds As DataSet
            Dim Filters As String = ""
            Dim Filters1 As String = ""
            Dim WhereStr As String = ""
            Dim OrderCols As String = ""
            Dim SumCount As Double = 0
            Dim SumTab As Double = 0
            Dim SumTabs As Double = 0
            Dim GoodsCount As Double = 0
            Dim StoreGoodsCount As Double = 0
            Filters = "GoodsBarcode='" & CurrentBarcode & "' and Batch='" & CurrentBatch & "' and StorePlace='" & CurrentStoreplace & "'"
            Filters1 = "GoodsBarcode='" & CurrentBarcode & "'"
            If Me.cmbOutStoreType.SelectedIndex <> 1 Then
                WhereStr = " and isnull(e.fBuJian,'')<>1 and isnull(e.fVirtual,'')<>1"
            Else
                WhereStr = " and isnull(e.fBuJian,'')<>1"
            End If

            sql = "select a.Period,a.StoreHouse,replace(a.Barcode,'*','') as Barcode,a.Batch,a.StorePlace,a.Goodsamount,b.Code,b.SupperItem,b.Enname,b.Cnname,c.ColorSName as Color,d.SizeSName as Spec from "
            sql += " (select Period,StoreHouse,BarCode,Batch,StorePlace,sum(Goodsamount) as Goodsamount from V_VisualStoreQuery   group by StoreHouse,Period,barcode,Batch,StorePlace) a"
            sql += " inner join BSC_Goods b on a.BarCode=b.BarCode"
            sql += " inner join BSC_ColorDefine c on b.Color=c.ColorCode "
            sql += " inner join BSC_SizeDefine d on b.Spec=d.SizeCode"
            sql += " left join BSC_Storage e on a.StorePlace=e.fStorageId"
            sql += " where a.StoreHouse='" & PubCompanyCode & "' and e.fCode='" & PubCompanyCode & "' and isnull(a.Goodsamount,0.00)>0" & WhereStr & " and a.BarCode='*" & CurrentBarcode & "*'  order by Batch asc,storePlace asc ,Goodsamount asc"
            m_Ds = New DataSet
            m_Ds = ReturnDataset(sql)
            ''查詢庫存
            If m_Ds.Tables(0).Rows.Count > 0 Then '’有庫存
                'Dim rows() As DataRow = dt.Select
                '’查找出當前庫位的信息
                Dim mRows() As DataRow = m_Ds.Tables(0).Select("Barcode='" & CurrentBarcode & "' and Batch='" & CurrentBatch & "' and storeplace='" & CurrentStoreplace & "'")
                If mRows.Length > 0 Then
                    '’當前庫位的數量
                    StoreGoodsCount = Convert.ToDouble(mRows(0).Item("Goodsamount"))

                    '’把當前庫位的放到GoodsCount
                    GoodsCount = Convert.ToDouble(mRows(0).Item("Goodsamount"))
                    ''如果 此庫位，此貨品，此批次下 已經填充的 SumCount 不為空
                    '’則把此數量放到SumCount
                    If DetailDS.Tables(0).Compute("sum(Goodsamount)", Filters) Is System.DBNull.Value Then
                        SumCount = 0.0
                    Else
                        SumCount = Convert.ToDouble(DetailDS.Tables(0).Compute("sum(Goodsamount)", Filters))
                    End If
                    '’ 比較 此庫位，此貨品，此批次下 已經填充的 SumCount 與IA單中的數量
                    If SumCount < CurrentGoodsamount Then
                        If MsgBox("[" & CurrentBarcode & "]庫位 [" & CurrentStoreplace & "] 庫存量不足，系統將從相臨的庫位扣除，是否繼續操作？", MsgBoxStyle.Question + MsgBoxStyle.OkOnly, Msg.CompanyName) = MsgBoxResult.Ok Then

                            '’比較每個庫位的情況   從查找出來的結果中的第2行到最後一行逐行比較
                            For i As Integer = 1 To m_Ds.Tables(0).Rows.Count - 1
                                Dim NewRow As DataRow = DetailDS.Tables(0).NewRow
                                '’計算庫存中從第2累開始每列的數量 
                                SumTab = Convert.ToDouble(m_Ds.Tables(0).Rows(i).Item("Goodsamount"))
                                '’計算庫存中從第2累開始每列的數量和
                                SumTabs += Convert.ToDouble(m_Ds.Tables(0).Rows(i).Item("Goodsamount"))
                                If Me.cmbOutStoreType.SelectedIndex = 2 Then ''一定是調撥入庫
                                    NewRow("PoNum") = Me.DGV_Detail.CurrentRow.Cells("PoNum").Value
                                    NewRow("PoNumItem") = Me.DGV_Detail.CurrentRow.Cells("PoNumItem")
                                    NewRow("GoodsBarCode") = m_Ds.Tables(0).Rows(i).Item("BarCode") & ""
                                    NewRow("GoodsCode") = m_Ds.Tables(0).Rows(i).Item("Code") & ""
                                    NewRow("SupperItem") = m_Ds.Tables(0).Rows(i).Item("SupperItem") & ""
                                    NewRow("GoodsName") = m_Ds.Tables(0).Rows(i).Item("Cnname") & ""
                                    NewRow("GoodsEname") = m_Ds.Tables(0).Rows(i).Item("Enname") & ""
                                    NewRow("GoodsSpec") = m_Ds.Tables(0).Rows(i).Item("Spec") & ""
                                    NewRow("Batch") = m_Ds.Tables(0).Rows(i).Item("batch") & ""
                                    NewRow("storeplace") = m_Ds.Tables(0).Rows(i).Item("storeplace") & ""
                                    If i = m_Ds.Tables(0).Rows.Count - 1 Then '‘如果到最後一個庫位了
                                        If CurrentGoodsamount > StoreGoodsCount + SumTabs Then '‘判斷總數是否夠 如果不夠
                                            GoodsCount = Convert.ToDouble(m_Ds.Tables(0).Rows(i).Item("Goodsamount"))
                                            NewRow("goodsamount") = Convert.ToDouble(m_Ds.Tables(0).Rows(i).Item("Goodsamount"))
                                            If Me.cmbOutStoreType.SelectedIndex = 4 Then
                                                DetailDS.Tables(0).Rows.InsertAt(NewRow, Me.DGV_Detail.CurrentRow.Index + 1)
                                            Else

                                                DetailDS.Tables(0).Rows.Add(NewRow)
                                            End If
                                            MsgBox("對不起，庫存量不足，請補充庫存！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                                            Exit For
                                        Else '’總數夠用
                                            GoodsCount = CurrentGoodsamount - StoreGoodsCount - (SumTabs - Convert.ToDouble(m_Ds.Tables(0).Rows(i).Item("Goodsamount")))
                                            NewRow("goodsamount") = GoodsCount
                                            If Me.cmbOutStoreType.SelectedIndex = 4 Then
                                                DetailDS.Tables(0).Rows.InsertAt(NewRow, Me.DGV_Detail.CurrentRow.Index + 1)
                                            Else
                                                DetailDS.Tables(0).Rows.Add(NewRow)
                                            End If
                                            Exit For
                                        End If
                                    Else '’如果查詢出來的不是最後一個庫位
                                        If CurrentGoodsamount - StoreGoodsCount > SumTabs Then '’此時加進來的庫位的數量不夠裝滿
                                            GoodsCount = Convert.ToDouble(m_Ds.Tables(0).Rows(i).Item("Goodsamount"))
                                            NewRow("goodsamount") = SumTab '’沒裝滿 把此庫位加上
                                            If Me.cmbOutStoreType.SelectedIndex = 4 Then
                                                DetailDS.Tables(0).Rows.InsertAt(NewRow, Me.DGV_Detail.CurrentRow.Index + 1)
                                            Else
                                                DetailDS.Tables(0).Rows.Add(NewRow)
                                            End If
                                            Continue For
                                        Else '’如果此時加進來的庫位的數量有多餘
                                            GoodsCount = CurrentGoodsamount - (StoreGoodsCount + SumTabs - Convert.ToDouble(m_Ds.Tables(0).Rows(i).Item("Goodsamount")))
                                            NewRow("goodsamount") = GoodsCount
                                            If Me.cmbOutStoreType.SelectedIndex = 4 Then
                                                DetailDS.Tables(0).Rows.InsertAt(NewRow, Me.DGV_Detail.CurrentRow.Index + 1)
                                            Else
                                                DetailDS.Tables(0).Rows.Add(NewRow)
                                            End If
                                            Exit For
                                        End If
                                    End If
                                End If
                            Next
                            If Me.cmbOutStoreType.SelectedIndex = 4 Then
                                If m_Ds.Tables(0).Rows.Count = 1 Then
                                    Me.DGV_Detail.CurrentRow.Cells("goodsamount").Value = GoodsCount
                                Else
                                    Me.DGV_Detail.CurrentRow.Cells("goodsamount").Value = CurrentGoodsamount - GoodsCount
                                End If
                            ElseIf Me.cmbOutStoreType.SelectedIndex = 0 Then
                                Me.DGV_Detail.CurrentRow.Cells("goodsamount").Value = StoreGoodsCount - (SumCount - CurrentGoodsamount)
                            Else
                                '‘Me.DGV_Detail.CurrentRow.Cells("goodsamount").Value = StoreGoodsCount
                            End If
                        End If
                    End If
                End If
            Else '’沒有庫存
                ' MessageBox.Show("" & CurrentBarcode & "沒有庫存", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information)
                MsgBox("對不起，" & CurrentBarcode & "庫存量不足，請補充庫存！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)

                Exit Sub
            End If
            Me.DGV_Sum.Rows(0).Cells("goodsamount").Value = Format(DetailDS.Tables(0).Compute("sum(goodsamount)", ""), "#0.00")
            For i As Integer = 0 To DetailDS.Tables(0).Rows.Count - 1
                DetailDS.Tables(0).Rows(i).Item("ItemNo") = Format(i + 1, "000")
            Next
            DetailDS.AcceptChanges()
            Me.DGV_Detail.DataSource = DetailDS.Tables(0)

            For i As Int16 = 0 To Me.DGV_Detail.Rows.Count - 2
                If Me.DGV_Detail.Rows(i).IsNewRow = False Then
                    If Me.DGV_Detail.Rows(i).Cells("GoodsBarCode").Value Is DBNull.Value Then
                        Me.DGV_Detail.Rows.RemoveAt(i)
                    End If
                End If
            Next
            DetailDS.AcceptChanges()
            Me.DGV_Detail.DataSource = DetailDS.Tables(0)
        End If

    End Sub

    Private Sub AutoAddNewRowIA(ByVal CurrentBarcode As String, ByVal CurrentBatch As String, ByVal CurrentStoreplace As String, ByVal CurrentGoodsamount As Integer, ByVal IANum As String)
        If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then

            Dim sql As String
            Dim m_Ds As DataSet
            Dim Filters As String = ""
            Dim Filters1 As String = ""
            Dim WhereStr As String = ""
            Dim OrderCols As String = ""
            Dim SumCount As Double = 0
            Dim SumTab As Double = 0
            Dim SumTabs As Double = 0
            Dim GoodsCount As Double = 0
            Dim StoreGoodsCount As Double = 0
            Filters = "GoodsBarcode='" & CurrentBarcode & "' and Batch='" & CurrentBatch & "' and StorePlace='" & CurrentStoreplace & "'"
            Filters1 = "GoodsBarcode='" & CurrentBarcode & "'"
            If Me.cmbOutStoreType.SelectedIndex <> 1 Then
                WhereStr = " and isnull(e.fBuJian,'')<>1 and isnull(e.fVirtual,'')<>1"
            Else
                WhereStr = " and isnull(e.fBuJian,'')<>1"
            End If

            sql = "select a.Period,a.StoreHouse,replace(a.Barcode,'*','') as Barcode,a.Batch,a.StorePlace,a.Goodsamount,b.Code,b.SupperItem,b.Enname,b.Cnname,c.ColorSName as Color,d.SizeSName as Spec from "
            sql += " (select Period,StoreHouse,BarCode,Batch,StorePlace,sum(Goodsamount) as Goodsamount from V_VisualStoreQuery   group by StoreHouse,Period,barcode,Batch,StorePlace) a"
            sql += " inner join BSC_Goods b on a.BarCode=b.BarCode"
            sql += " inner join BSC_ColorDefine c on b.Color=c.ColorCode "
            sql += " inner join BSC_SizeDefine d on b.Spec=d.SizeCode"
            sql += " left join BSC_Storage e on a.StorePlace=e.fStorageId"
            sql += " where a.StoreHouse='" & PubCompanyCode & "' and e.fCode='" & PubCompanyCode & "' and isnull(a.Goodsamount,0.00)>0" & WhereStr & " and a.BarCode='*" & CurrentBarcode & "*'  order by Batch asc,storePlace asc ,Goodsamount asc"
            m_Ds = New DataSet
            m_Ds = ReturnDataset(sql)
            ''查詢庫存
            If m_Ds.Tables(0).Rows.Count > 0 Then '’有庫存
                'Dim rows() As DataRow = dt.Select
                '’查找出當前庫位的信息
                Dim mRows() As DataRow = m_Ds.Tables(0).Select("Barcode='" & CurrentBarcode & "' and Batch='" & CurrentBatch & "' and storeplace='" & CurrentStoreplace & "'")
                If mRows.Length > 0 Then
                    '’當前庫位的數量
                    StoreGoodsCount = Convert.ToDouble(mRows(0).Item("Goodsamount"))

                    '’把當前庫位的放到GoodsCount
                    GoodsCount = Convert.ToDouble(mRows(0).Item("Goodsamount"))
                    ''如果 此庫位，此貨品，此批次下 已經填充的 SumCount 不為空
                    '’則把此數量放到SumCount
                    If DetailDS.Tables(0).Compute("sum(Goodsamount)", Filters) Is System.DBNull.Value Then
                        SumCount = 0.0
                    Else
                        SumCount = Convert.ToDouble(DetailDS.Tables(0).Compute("sum(Goodsamount)", Filters))
                    End If
                    '’ 比較 此庫位，此貨品，此批次下 已經填充的 SumCount 與IA單中的數量
                    If SumCount < CurrentGoodsamount Then
                        If MsgBox("[" & CurrentBarcode & "]庫位 [" & CurrentStoreplace & "] 庫存量不足，系統將從相臨的庫位扣除，是否繼續操作？", MsgBoxStyle.Question + MsgBoxStyle.OkOnly, Msg.CompanyName) = MsgBoxResult.Ok Then

                            '’比較每個庫位的情況   從查找出來的結果中的第2行到最後一行逐行比較
                            For i As Integer = 1 To m_Ds.Tables(0).Rows.Count - 1
                                Dim NewRow As DataRow = DetailDS.Tables(0).NewRow
                                '’計算庫存中從第2累開始每列的數量 
                                SumTab = Convert.ToDouble(m_Ds.Tables(0).Rows(i).Item("Goodsamount"))
                                '’計算庫存中從第2累開始每列的數量和
                                SumTabs += Convert.ToDouble(m_Ds.Tables(0).Rows(i).Item("Goodsamount"))
                                If Me.cmbOutStoreType.SelectedIndex = 2 Then ''一定是調撥入庫
                                    NewRow("PoNum") = IANum
                                    NewRow("PoNumItem") = Me.DGV_Detail.CurrentRow.Cells("PoNumItem")
                                    NewRow("GoodsBarCode") = m_Ds.Tables(0).Rows(i).Item("BarCode") & ""
                                    NewRow("GoodsCode") = m_Ds.Tables(0).Rows(i).Item("Code") & ""
                                    NewRow("SupperItem") = m_Ds.Tables(0).Rows(i).Item("SupperItem") & ""
                                    NewRow("GoodsName") = m_Ds.Tables(0).Rows(i).Item("Cnname") & ""
                                    NewRow("GoodsEname") = m_Ds.Tables(0).Rows(i).Item("Enname") & ""
                                    NewRow("GoodsSpec") = m_Ds.Tables(0).Rows(i).Item("Spec") & ""
                                    NewRow("Batch") = m_Ds.Tables(0).Rows(i).Item("batch") & ""
                                    NewRow("storeplace") = m_Ds.Tables(0).Rows(i).Item("storeplace") & ""
                                    If i = m_Ds.Tables(0).Rows.Count - 1 Then '‘如果到最後一個庫位了
                                        If CurrentGoodsamount > StoreGoodsCount + SumTabs Then '‘判斷總數是否夠 如果不夠
                                            GoodsCount = Convert.ToDouble(m_Ds.Tables(0).Rows(i).Item("Goodsamount"))
                                            NewRow("goodsamount") = Convert.ToDouble(m_Ds.Tables(0).Rows(i).Item("Goodsamount"))
                                            If Me.cmbOutStoreType.SelectedIndex = 4 Then
                                                DetailDS.Tables(0).Rows.InsertAt(NewRow, Me.DGV_Detail.CurrentRow.Index + 1)
                                            Else

                                                DetailDS.Tables(0).Rows.Add(NewRow)
                                            End If
                                            MsgBox("對不起，庫存量不足，請補充庫存！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                                            Exit For
                                        Else '’總數夠用
                                            GoodsCount = CurrentGoodsamount - StoreGoodsCount - (SumTabs - Convert.ToDouble(m_Ds.Tables(0).Rows(i).Item("Goodsamount")))
                                            NewRow("goodsamount") = GoodsCount
                                            If Me.cmbOutStoreType.SelectedIndex = 4 Then
                                                DetailDS.Tables(0).Rows.InsertAt(NewRow, Me.DGV_Detail.CurrentRow.Index + 1)
                                            Else
                                                DetailDS.Tables(0).Rows.Add(NewRow)
                                            End If
                                            Exit For
                                        End If
                                    Else '’如果查詢出來的不是最後一個庫位
                                        If CurrentGoodsamount - StoreGoodsCount > SumTabs Then '’此時加進來的庫位的數量不夠裝滿
                                            GoodsCount = Convert.ToDouble(m_Ds.Tables(0).Rows(i).Item("Goodsamount"))
                                            NewRow("goodsamount") = SumTab '’沒裝滿 把此庫位加上
                                            If Me.cmbOutStoreType.SelectedIndex = 4 Then
                                                DetailDS.Tables(0).Rows.InsertAt(NewRow, Me.DGV_Detail.CurrentRow.Index + 1)
                                            Else
                                                DetailDS.Tables(0).Rows.Add(NewRow)
                                            End If
                                            Continue For
                                        Else '’如果此時加進來的庫位的數量有多餘
                                            GoodsCount = CurrentGoodsamount - (StoreGoodsCount + SumTabs - Convert.ToDouble(m_Ds.Tables(0).Rows(i).Item("Goodsamount")))
                                            NewRow("goodsamount") = GoodsCount
                                            If Me.cmbOutStoreType.SelectedIndex = 4 Then
                                                DetailDS.Tables(0).Rows.InsertAt(NewRow, Me.DGV_Detail.CurrentRow.Index + 1)
                                            Else
                                                DetailDS.Tables(0).Rows.Add(NewRow)
                                            End If
                                            Exit For
                                        End If
                                    End If
                                End If
                            Next
                            If Me.cmbOutStoreType.SelectedIndex = 4 Then
                                If m_Ds.Tables(0).Rows.Count = 1 Then
                                    Me.DGV_Detail.CurrentRow.Cells("goodsamount").Value = GoodsCount
                                Else
                                    Me.DGV_Detail.CurrentRow.Cells("goodsamount").Value = CurrentGoodsamount - GoodsCount
                                End If
                            ElseIf Me.cmbOutStoreType.SelectedIndex = 0 Then
                                Me.DGV_Detail.CurrentRow.Cells("goodsamount").Value = StoreGoodsCount - (SumCount - CurrentGoodsamount)
                            Else
                                '‘Me.DGV_Detail.CurrentRow.Cells("goodsamount").Value = StoreGoodsCount
                            End If
                        End If
                    End If
                End If
            Else '’沒有庫存
                ' MessageBox.Show("" & CurrentBarcode & "沒有庫存", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information)
                MsgBox("對不起，" & CurrentBarcode & "庫存量不足，請補充庫存！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)

                Exit Sub
            End If
            Me.DGV_Sum.Rows(0).Cells("goodsamount").Value = Format(DetailDS.Tables(0).Compute("sum(goodsamount)", ""), "#0.00")
            For i As Integer = 0 To DetailDS.Tables(0).Rows.Count - 1
                DetailDS.Tables(0).Rows(i).Item("ItemNo") = Format(i + 1, "000")
            Next
            DetailDS.AcceptChanges()
            Me.DGV_Detail.DataSource = DetailDS.Tables(0)

            For i As Int16 = 0 To Me.DGV_Detail.Rows.Count - 2
                If Me.DGV_Detail.Rows(i).IsNewRow = False Then
                    If Me.DGV_Detail.Rows(i).Cells("GoodsBarCode").Value Is DBNull.Value Then
                        Me.DGV_Detail.Rows.RemoveAt(i)
                    End If
                End If
            Next
            DetailDS.AcceptChanges()
            Me.DGV_Detail.DataSource = DetailDS.Tables(0)
        End If

    End Sub

    Private Sub DGV_Detail_CellValueChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DGV_Detail.CellValueChanged
        Try
            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
                If e.ColumnIndex = 9 Then
                    Dim sql As String
                    Dim m_Ds As DataSet
                    Dim CurrentBarcode As String = ""
                    Dim CurrentBatch As String = ""
                    Dim CurrentStoreplace As String = ""
                    Dim CurrentGoodsamount As Double = 0
                    Dim Filters As String = ""
                    Dim Filters1 As String = ""
                    Dim WhereStr As String = ""
                    Dim OrderCols As String = ""
                    Dim SumCount As Double = 0
                    Dim SumTab As Double = 0
                    Dim GoodsCount As Double = 0
                    Dim StoreGoodsCount As Double = 0
                    If Not Me.DGV_Detail.CurrentRow.Cells("GoodsBarCode").Value Is System.DBNull.Value Then
                        CurrentBarcode = Me.DGV_Detail.CurrentRow.Cells("GoodsBarCode").Value
                    End If
                    If Not Me.DGV_Detail.CurrentRow.Cells("Batch").Value Is DBNull.Value Then
                        CurrentBatch = Me.DGV_Detail.CurrentRow.Cells("Batch").Value
                    End If
                    If Not Me.DGV_Detail.CurrentRow.Cells("storeplace").Value Is DBNull.Value Then
                        CurrentStoreplace = Me.DGV_Detail.CurrentRow.Cells("storeplace").Value
                    End If
                    If Convert.ToDouble(Me.DGV_Detail.CurrentRow.Cells("goodsamount").Value) <> 0 Then
                        CurrentGoodsamount = Convert.ToDouble(Me.DGV_Detail.CurrentRow.Cells("goodsamount").Value)
                    End If
                    Filters = "GoodsBarcode='" & CurrentBarcode & "' and Batch='" & CurrentBatch & "' and StorePlace='" & CurrentStoreplace & "'"
                    Filters1 = "GoodsBarcode='" & CurrentBarcode & "'"
                    If Me.cmbOutStoreType.SelectedIndex <> 1 Then
                        WhereStr = " and isnull(e.fBuJian,'')<>1 and isnull(e.fVirtual,'')<>1"
                    Else
                        WhereStr = " and isnull(e.fBuJian,'')<>1"
                    End If

                    sql = "select a.Period,a.StoreHouse,replace(a.Barcode,'*','') as Barcode,a.Batch,a.StorePlace,a.Goodsamount,b.Code,b.SupperItem,b.Enname,b.Cnname,c.ColorSName as Color,d.SizeSName as Spec from "
                    sql += " (select Period,StoreHouse,BarCode,Batch,StorePlace,sum(Goodsamount) as Goodsamount from V_VisualStoreQuery   group by StoreHouse,Period,barcode,Batch,StorePlace) a"
                    sql += " inner join BSC_Goods b on a.BarCode=b.BarCode"
                    sql += " inner join BSC_ColorDefine c on b.Color=c.ColorCode "
                    sql += " inner join BSC_SizeDefine d on b.Spec=d.SizeCode"
                    sql += " left join BSC_Storage e on a.StorePlace=e.fStorageId"
                    sql += " where a.StoreHouse='" & PubCompanyCode & "' and e.fCode='" & PubCompanyCode & "' and isnull(a.Goodsamount,0.00)>0" & WhereStr & " and a.BarCode='*" & CurrentBarcode & "*' order by substring(Batch,4,3),substring(Batch,1,3),Goodsamount"
                    m_Ds = New DataSet
                    m_Ds = ReturnDataset(sql)
                    If m_Ds.Tables(0).Rows.Count > 0 Then
                        Dim mRows() As DataRow = m_Ds.Tables(0).Select("Barcode='" & CurrentBarcode & "' and Batch='" & CurrentBatch & "' and storeplace='" & CurrentStoreplace & "'")
                        If mRows.Length > 0 Then
                            StoreGoodsCount = Convert.ToDouble(mRows(0).Item("Goodsamount"))
                            GoodsCount = Convert.ToDouble(mRows(0).Item("Goodsamount"))
                            If DetailDS.Tables(0).Compute("sum(Goodsamount)", Filters) Is System.DBNull.Value Then
                                SumCount = 0.0
                            Else
                                SumCount = Convert.ToDouble(DetailDS.Tables(0).Compute("sum(Goodsamount)", Filters))
                            End If
                            If (SumCount) > StoreGoodsCount Then
                                If MsgBox("庫位 [" & CurrentStoreplace & "] 庫存量不足，系統將從相臨的庫位扣除，是否繼續操作？", MsgBoxStyle.Question + MsgBoxStyle.OkOnly, Msg.CompanyName) = MsgBoxResult.Ok Then

                                    For i As Integer = 1 To m_Ds.Tables(0).Rows.Count - 1


                                        Dim NewRow As DataRow = DetailDS.Tables(0).NewRow
                                        SumTab += Convert.ToDouble(m_Ds.Tables(0).Rows(i).Item("Goodsamount"))
                                        If Me.cmbOutStoreType.SelectedIndex = 4 Then
                                            NewRow("PoNum") = Me.DGV_Detail.CurrentRow.Cells("PoNum").Value
                                            NewRow("PoNumItem") = Me.DGV_Detail.CurrentRow.Cells("PoNumItem").Value
                                        End If
                                        NewRow("GoodsBarCode") = m_Ds.Tables(0).Rows(i).Item("BarCode") & ""
                                        NewRow("GoodsCode") = m_Ds.Tables(0).Rows(i).Item("Code") & ""
                                        NewRow("SupperItem") = m_Ds.Tables(0).Rows(i).Item("SupperItem") & ""
                                        NewRow("GoodsName") = m_Ds.Tables(0).Rows(i).Item("Cnname") & ""
                                        NewRow("GoodsEname") = m_Ds.Tables(0).Rows(i).Item("Enname") & ""
                                        NewRow("GoodsSpec") = m_Ds.Tables(0).Rows(i).Item("Spec") & ""
                                        NewRow("Batch") = m_Ds.Tables(0).Rows(i).Item("batch") & ""
                                        NewRow("storeplace") = m_Ds.Tables(0).Rows(i).Item("storeplace") & ""
                                        If i = m_Ds.Tables(0).Rows.Count - 1 Then
                                            If SumCount > StoreGoodsCount + SumTab Then
                                                GoodsCount = Convert.ToDouble(m_Ds.Tables(0).Rows(i).Item("Goodsamount"))
                                                NewRow("goodsamount") = Convert.ToDouble(m_Ds.Tables(0).Rows(i).Item("Goodsamount"))
                                                If Me.cmbOutStoreType.SelectedIndex = 4 Then
                                                    DetailDS.Tables(0).Rows.InsertAt(NewRow, Me.DGV_Detail.CurrentRow.Index + 1)
                                                Else
                                                    DetailDS.Tables(0).Rows.Add(NewRow)
                                                End If
                                                MsgBox("對不起，庫存量不足，請補充庫存！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                                                Exit For
                                            Else
                                                GoodsCount = SumCount - (StoreGoodsCount + SumTab - Convert.ToDouble(m_Ds.Tables(0).Rows(i).Item("Goodsamount")))
                                                NewRow("goodsamount") = GoodsCount
                                                If Me.cmbOutStoreType.SelectedIndex = 4 Then
                                                    DetailDS.Tables(0).Rows.InsertAt(NewRow, Me.DGV_Detail.CurrentRow.Index + 1)
                                                Else
                                                    DetailDS.Tables(0).Rows.Add(NewRow)
                                                End If
                                                Exit For
                                            End If
                                        Else
                                            If SumCount - StoreGoodsCount > SumTab Then
                                                GoodsCount = Convert.ToDouble(m_Ds.Tables(0).Rows(i).Item("Goodsamount"))
                                                NewRow("goodsamount") = GoodsCount
                                                If Me.cmbOutStoreType.SelectedIndex = 4 Then
                                                    DetailDS.Tables(0).Rows.InsertAt(NewRow, Me.DGV_Detail.CurrentRow.Index + 1)
                                                Else
                                                    DetailDS.Tables(0).Rows.Add(NewRow)
                                                End If
                                                Continue For
                                            Else
                                                GoodsCount = SumCount - (StoreGoodsCount + SumTab - Convert.ToDouble(m_Ds.Tables(0).Rows(i).Item("Goodsamount")))
                                                NewRow("goodsamount") = GoodsCount
                                                If Me.cmbOutStoreType.SelectedIndex = 4 Then
                                                    DetailDS.Tables(0).Rows.InsertAt(NewRow, Me.DGV_Detail.CurrentRow.Index + 1)
                                                Else
                                                    DetailDS.Tables(0).Rows.Add(NewRow)
                                                End If
                                                Exit For
                                            End If
                                        End If
                                    Next
                                    If Me.cmbOutStoreType.SelectedIndex = 4 Then
                                        If m_Ds.Tables(0).Rows.Count = 1 Then
                                            Me.DGV_Detail.CurrentRow.Cells("goodsamount").Value = GoodsCount
                                        Else
                                            Me.DGV_Detail.CurrentRow.Cells("goodsamount").Value = CurrentGoodsamount - GoodsCount
                                        End If
                                    ElseIf Me.cmbOutStoreType.SelectedIndex = 0 Then
                                        Me.DGV_Detail.CurrentRow.Cells("goodsamount").Value = StoreGoodsCount - (SumCount - CurrentGoodsamount)
                                    Else
                                        Me.DGV_Detail.CurrentRow.Cells("goodsamount").Value = StoreGoodsCount
                                    End If
                                End If
                            End If
                        End If
                    End If

                    Me.DGV_Sum.Rows(0).Cells("goodsamount").Value = Format(DetailDS.Tables(0).Compute("sum(goodsamount)", ""), "#0.00")
                    For i As Integer = 0 To DetailDS.Tables(0).Rows.Count - 1
                        DetailDS.Tables(0).Rows(i).Item("ItemNo") = Format(i + 1, "000")
                    Next
                    DetailDS.AcceptChanges()
                    Me.DGV_Detail.DataSource = DetailDS.Tables(0)

                    For i As Int16 = 0 To Me.DGV_Detail.Rows.Count - 2
                        If Me.DGV_Detail.Rows(i).IsNewRow = False Then
                            If Me.DGV_Detail.Rows(i).Cells("GoodsBarCode").Value Is DBNull.Value Then
                                Me.DGV_Detail.Rows.RemoveAt(i)
                            End If
                        End If
                    Next
                    DetailDS.AcceptChanges()
                    Me.DGV_Detail.DataSource = DetailDS.Tables(0)
                End If
            End If
        Catch ex As Exception
            MsgBox("DGV_Detail_CellValueChanged:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub DGV_Detail_ColumnWidthChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewColumnEventArgs) Handles DGV_Detail.ColumnWidthChanged
        SetGridWidth()
    End Sub

    Private Sub DGV_Detail_Scroll(ByVal sender As Object, ByVal e As System.Windows.Forms.ScrollEventArgs) Handles DGV_Detail.Scroll
        'Me.DGV_Sum.FirstDisplayedScrollingColumnIndex = Me.DGV_Detail.FirstDisplayedScrollingColumnIndex
        Me.DGV_Sum.HorizontalScrollingOffset = Me.DGV_Detail.HorizontalScrollingOffset
    End Sub

    Private Sub DGV_Detail_KeyDown1(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles DGV_Detail.KeyDown
        Try
            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
                Select Case e.KeyCode
                    Case Keys.Delete
                        Dim CurrentID As String = Me.DGV_Detail.CurrentRow.Cells("ItemNo").Value
                        If CurrentID.Length > 0 Then
                            If MsgBox(My.Resources.ConfirmDelete, MsgBoxStyle.Question + MsgBoxStyle.OkCancel, Msg.CompanyName) = MsgBoxResult.Ok Then
                                Dim Rows() As DataRow = DetailDS.Tables(0).Select("ItemNo='" & CurrentID & "'")
                                If Rows.Length > 0 Then
                                    DetailDS.Tables(0).Rows.Remove(Rows(0))
                                End If
                            End If
                            For i As Integer = 0 To DetailDS.Tables(0).Rows.Count - 1
                                DetailDS.Tables(0).Rows(i).Item("ItemNo") = Format(i + 1, "000")
                            Next
                            DetailDS.AcceptChanges()
                            Me.DGV_Detail.DataSource = DetailDS.Tables(0)
                            If DetailDS.Tables(0).Rows.Count > 0 Then
                                If Not DetailDS.Tables(0).Rows(0).Item("Goodsamount") Is DBNull.Value Then
                                    Me.DGV_Sum.Rows(0).Cells("goodsamount").Value = Format(DetailDS.Tables(0).Compute("sum(goodsamount)", ""), "#0.00")
                                End If
                            End If
                        End If
                    Case Keys.D1
                        If e.Control = True Then
                            If Me.DGV_Detail.CurrentCell.ColumnIndex = 2 Then
                                Dim Frm_SelectGoods As New Frm_SelectGoods
                                Frm_SelectGoods.Index = 1
                                Frm_SelectGoods.ShowDialog()
                                If Frm_SelectGoods.BarCode Is Nothing Then
                                    Exit Sub
                                End If
                                Dim BarCode As String = Frm_SelectGoods.BarCode
                                If BarCode = "" Or BarCode.Length <= 0 Then
                                    Exit Sub
                                End If
                                AddDataToGrid(BarCode)
                                If DetailDS.Tables(0).Rows.Count > 0 Then
                                    Me.DGV_Detail.Focus()
                                    Me.DGV_Detail.CurrentCell = Me.DGV_Detail.Rows(Me.DGV_Detail.CurrentRow.Index).Cells("goodsamount")
                                End If
                                Me.DGV_Sum.Rows(0).Cells("goodsamount").Value = Format(DetailDS.Tables(0).Compute("sum(goodsamount)", ""), "#0.00")
                            End If
                        End If
                End Select
            End If
        Catch ex As Exception
            MsgBox("DGV_Detail_KeyDown:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub DGV_Detail_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles DGV_Detail.KeyUp

        Try

        Catch ex As Exception
            MsgBox("DGV_Detail_KeyUp:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub DGV_Master_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DGV_Master.CellClick
        SetToolEnable()
    End Sub

    Private Sub DGV_Master_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles DGV_Master.DoubleClick
        Me.TabControl1.SelectedIndex = 1
    End Sub

    Private Sub btnelement_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnelement.Click

        Try
            If lstviewelement.Items.Count = 0 Then
                MsgBox("沒有可以選擇的元件")
            ElseIf lstviewelement.Items.Count = 1 Then
                Me.lstviewelement.Items(0).Checked = True
            Else
                For i As Integer = 0 To lstviewelement.Items.Count - 1
                    Me.lstviewelement.Items(i).Checked = True
                Next

            End If
        Catch ex As Exception
            MsgBox("btnelement_Click" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Function Isselectedelement() As Boolean
        If lstviewelement.Visible = True Then
            If lstviewelement.SelectedItems.Count < 1 Then
                Return False
            Else
                Return True
            End If
        Else
            Return False
        End If
    End Function

    Private Sub cmbFromStore_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmbFromStore.SelectedIndexChanged
        Try
            If Me.TabControl1.SelectedIndex = 1 Then
                If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
                    Dim sql As String = ""
                    Dim FromStore As String = Me.cmbFromStore.SelectedValue.ToString
                    Dim m_DS As New DataSet
                    sql = "select distinct(Replace(b.GoodsBarcode,'*','')) as GoodsBarCode from Stor_TradeMaster a inner join Stor_TradeDetail b on a.bonum=b.bonum where a.TradeType='+' and a.ToStore='" & FromStore & "'"

                    m_DS = ReturnDataset(sql)
                    Me.cmbGoodsBarcode.Text = ""
                    Me.cmbGoodsBarcode.DisplayMember = "GoodsBarcode"
                    Me.cmbGoodsBarcode.ValueMember = "GoodsBarCode"
                    Me.cmbGoodsBarcode.DataSource = m_DS.Tables(0)
                    Dim Rows() As DataRow = StoreDS.Tables(2).Select("fCode='" & FromStore & "'")
                    If Rows.Length > 0 Then
                        IsPlace = Rows(0).Item("fStorePlace")
                    End If
                    If IsPlace = True Then
                    Else
                        Me.cmbStorePlace.Enabled = False
                    End If
                End If
            End If

        Catch ex As Exception
            MsgBox("cmbFromStore_SelectedIndexChanged:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub cmbGoodsBarcode_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmbGoodsBarcode.SelectedIndexChanged

        Try
            If Me.TabControl1.SelectedIndex = 1 Then
                Dim sql As String = ""
                Dim GoodsBarCode As String = Me.cmbGoodsBarcode.SelectedValue & ""
                Dim m_DS As New DataSet
                sql = "select distinct(b.Batch) from Stor_TradeMaster a inner join Stor_TradeDetail b on a.bonum=b.bonum where a.TradeType='+' and b.GoodsBarCode='*" & GoodsBarCode & "*'"
                m_DS = ReturnDataset(sql)

                Me.cmbBatch.Text = ""
                Me.cmbBatch.DisplayMember = "Batch"
                Me.cmbBatch.ValueMember = "Batch"
                Me.cmbBatch.DataSource = m_DS.Tables(0)
            End If
        Catch ex As Exception
            MsgBox("cmbGoodsBarcode_SelectedIndexChanged:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub cmbGoodsBarcode_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles cmbGoodsBarcode.KeyDown

        If e.KeyCode = Keys.Shift Then
            e.Handled = True
            If e.KeyCode = Keys.Enter Then
                SendKeys.Send("+{TAB}")
                SendKeys.Send("{F4}")
            End If
        Else
            Select Case e.KeyCode
                Case Keys.Enter
                    SendKeys.Send("{TAB}")
                    SendKeys.Send("{F4}")
                Case Keys.D1
                    If e.Control = True Then
                        Dim Frm_SelectGoods As New Frm_SelectGoods
                        Frm_SelectGoods.Index = 1
                        Frm_SelectGoods.ShowDialog()
                        If Frm_SelectGoods.BarCode Is Nothing Then
                            Exit Sub
                        End If
                        Dim BarCode As String = Frm_SelectGoods.BarCode
                        If BarCode = "" Or BarCode.Length <= 0 Then
                            Exit Sub
                        End If
                        Me.cmbGoodsBarcode.Text = BarCode.Replace("^", "")
                        LoadGoodsBarCode(BarCode)
                    End If
            End Select
        End If

    End Sub

    Private Sub cmbBatch_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmbBatch.SelectedIndexChanged
        Try
            If Me.TabControl1.SelectedIndex = 1 Then

                If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then

                    If StorePlaceDS Is Nothing Then
                        Exit Sub
                    End If

                    Dim Batch As String = Me.cmbBatch.SelectedValue & ""

                    Dim Rows() As DataRow = StorePlaceDS.Tables(0).Select("Batch='" & Batch & "'")

                    If Rows.Length > 0 Then
                        Me.cmbStorePlace.Items.Clear()
                        For Each mRow As DataRow In Rows
                            Me.cmbStorePlace.Items.Add(mRow("StorePlace"))
                        Next
                        Me.cmbStorePlace.SelectedIndex = 0
                    End If
                End If
            End If
        Catch ex As Exception
            MsgBox("cmbBatch_SelectedIndexChanged:" + ex.ToString & ex.StackTrace, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub cmbFromStore1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)

        Try
            If Me.TabControl1.SelectedIndex = 2 Then
                'Dim FromStore As String = Me.cmbFromStore1.SelectedValue.ToString
                'Dim Rows() As DataRow = StoreDS.Tables(2).Select("fCode='" & FromStore & "'")
                'If Rows.Length > 0 Then
                '    IsPlace1 = Rows(0).Item("fStorePlace")
                'End If
                'If IsPlace1 = True Then
                '    txtplace.Enabled = True
                'Else
                '    txtplace.Enabled = False
                'End If
            End If
        Catch ex As Exception
            MsgBox("cmbFromStore1_SelectedIndexChanged:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub DGV_Master_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles DGV_Master.KeyDown

        Dim StoreHouse As String = ""
        Dim DeliverDate As String = ""
        Select Case e.KeyCode
            Case Keys.Up
                If Me.DGV_Master.CurrentRow.Index - 1 < 0 Then
                    Exit Select
                End If
                StoreHouse = Me.DGV_Master.Rows(Me.DGV_Master.CurrentRow.Index - 1).Cells("FromStore").Value
                DeliverDate = Me.DGV_Master.Rows(Me.DGV_Master.CurrentRow.Index - 1).Cells("DeliverDate").Value.ToString.Replace("-", "").Substring(0, 6)

                If Me.DGV_Master.Rows(Me.DGV_Master.CurrentRow.Index - 1).Cells("BoStatus").Value = "保存" Then
                    MainForm.ToolStripPrint.Enabled = False
                    If StoreHouse = PubCompanyName Then
                        MainForm.ToolStripCheck.Enabled = True And CheckEnable = True
                        MainForm.ToolStripUnCheck.Enabled = False
                        MainForm.ToolStripComplete.Enabled = False
                        MainForm.ToolStripDelete.Enabled = True And DeleteEnable = True
                        MainForm.ToolStripEdit.Enabled = True And EditEnable = True
                    Else
                        MainForm.ToolStripCheck.Enabled = False
                        MainForm.ToolStripUnCheck.Enabled = False
                        MainForm.ToolStripComplete.Enabled = False
                        MainForm.ToolStripDelete.Enabled = False
                        MainForm.ToolStripEdit.Enabled = False
                    End If
                ElseIf Me.DGV_Master.Rows(Me.DGV_Master.CurrentRow.Index - 1).Cells("BoStatus").Value = "核准" Then
                    If StoreHouse = PubCompanyName Then
                        MainForm.ToolStripPrint.Enabled = True
                        MainForm.ToolStripCheck.Enabled = False
                        If DeliverDate < PeriodData Then
                            MainForm.ToolStripUnCheck.Enabled = False
                        Else
                            MainForm.ToolStripUnCheck.Enabled = True And UncheckEnable = True
                        End If
                        MainForm.ToolStripComplete.Enabled = True And CompleteEnable = True
                        MainForm.ToolStripDelete.Enabled = False
                        MainForm.ToolStripEdit.Enabled = False
                    Else
                        MainForm.ToolStripPrint.Enabled = False
                        MainForm.ToolStripCheck.Enabled = False
                        MainForm.ToolStripUnCheck.Enabled = False
                        MainForm.ToolStripComplete.Enabled = False
                        MainForm.ToolStripDelete.Enabled = False
                        MainForm.ToolStripEdit.Enabled = False
                    End If
                ElseIf Me.DGV_Master.Rows(Me.DGV_Master.CurrentRow.Index - 1).Cells("BoStatus").Value = "反核准" Then
                    MainForm.ToolStripPrint.Enabled = False
                    If StoreHouse = PubCompanyName Then
                        MainForm.ToolStripCheck.Enabled = True And CheckEnable = True
                        MainForm.ToolStripUnCheck.Enabled = False
                        MainForm.ToolStripComplete.Enabled = False
                        MainForm.ToolStripDelete.Enabled = True And DeleteEnable = True And UncheckEnable = True
                        MainForm.ToolStripEdit.Enabled = True And EditEnable = True
                    Else
                        MainForm.ToolStripCheck.Enabled = False
                        MainForm.ToolStripUnCheck.Enabled = False
                        MainForm.ToolStripComplete.Enabled = False
                        MainForm.ToolStripDelete.Enabled = False
                        MainForm.ToolStripEdit.Enabled = False
                    End If
                ElseIf Me.DGV_Master.Rows(Me.DGV_Master.CurrentRow.Index - 1).Cells("BoStatus").Value = "結案" Then
                    MainForm.ToolStripPrint.Enabled = True
                    MainForm.ToolStripCheck.Enabled = False
                    MainForm.ToolStripUnCheck.Enabled = False
                    MainForm.ToolStripComplete.Enabled = False
                    MainForm.ToolStripDelete.Enabled = False
                    MainForm.ToolStripEdit.Enabled = False
                End If
            Case Keys.Down
                If Me.DGV_Master.CurrentRow.Index + 1 >= Me.DGV_Master.RowCount Then
                    Exit Select
                End If
                StoreHouse = Me.DGV_Master.Rows(Me.DGV_Master.CurrentRow.Index + 1).Cells("FromStore").Value
                DeliverDate = Me.DGV_Master.Rows(Me.DGV_Master.CurrentRow.Index + 1).Cells("DeliverDate").Value.ToString.Replace("-", "").Substring(0, 6)

                If Me.DGV_Master.Rows(Me.DGV_Master.CurrentRow.Index + 1).Cells("BoStatus").Value = "保存" Then
                    MainForm.ToolStripPrint.Enabled = False
                    If StoreHouse = PubCompanyName Then
                        MainForm.ToolStripCheck.Enabled = True And CheckEnable = True
                        MainForm.ToolStripUnCheck.Enabled = False
                        MainForm.ToolStripComplete.Enabled = False
                        MainForm.ToolStripDelete.Enabled = True And DeleteEnable = True
                        MainForm.ToolStripEdit.Enabled = True And EditEnable = True
                    Else
                        MainForm.ToolStripCheck.Enabled = False
                        MainForm.ToolStripUnCheck.Enabled = False
                        MainForm.ToolStripComplete.Enabled = False
                        MainForm.ToolStripDelete.Enabled = False
                        MainForm.ToolStripEdit.Enabled = False
                    End If
                ElseIf Me.DGV_Master.Rows(Me.DGV_Master.CurrentRow.Index + 1).Cells("BoStatus").Value = "核准" Then
                    If StoreHouse = PubCompanyName Then
                        MainForm.ToolStripPrint.Enabled = True
                        MainForm.ToolStripCheck.Enabled = False
                        If DeliverDate < PeriodData Then
                            MainForm.ToolStripUnCheck.Enabled = False
                        Else
                            MainForm.ToolStripUnCheck.Enabled = True And UncheckEnable = True
                        End If
                        MainForm.ToolStripComplete.Enabled = True And CompleteEnable = True
                        MainForm.ToolStripDelete.Enabled = False
                        MainForm.ToolStripEdit.Enabled = False
                    Else
                        MainForm.ToolStripPrint.Enabled = False
                        MainForm.ToolStripCheck.Enabled = False
                        MainForm.ToolStripUnCheck.Enabled = False
                        MainForm.ToolStripComplete.Enabled = False
                        MainForm.ToolStripDelete.Enabled = False
                        MainForm.ToolStripEdit.Enabled = False
                    End If
                ElseIf Me.DGV_Master.Rows(Me.DGV_Master.CurrentRow.Index + 1).Cells("BoStatus").Value = "反核准" Then
                    MainForm.ToolStripPrint.Enabled = False
                    If StoreHouse = PubCompanyName Then
                        MainForm.ToolStripCheck.Enabled = True And CheckEnable = True
                        MainForm.ToolStripUnCheck.Enabled = False
                        MainForm.ToolStripComplete.Enabled = False
                        MainForm.ToolStripDelete.Enabled = True And DeleteEnable = True And UncheckEnable = True
                        MainForm.ToolStripEdit.Enabled = True And EditEnable = True
                    Else
                        MainForm.ToolStripCheck.Enabled = False
                        MainForm.ToolStripUnCheck.Enabled = False
                        MainForm.ToolStripComplete.Enabled = False
                        MainForm.ToolStripDelete.Enabled = False
                        MainForm.ToolStripEdit.Enabled = False
                    End If
                ElseIf Me.DGV_Master.Rows(Me.DGV_Master.CurrentRow.Index + 1).Cells("BoStatus").Value = "結案" Then
                    MainForm.ToolStripPrint.Enabled = True
                    MainForm.ToolStripCheck.Enabled = False
                    MainForm.ToolStripUnCheck.Enabled = False
                    MainForm.ToolStripComplete.Enabled = False
                    MainForm.ToolStripDelete.Enabled = False
                    MainForm.ToolStripEdit.Enabled = False
                End If
            Case Keys.Delete
                ActionDelete()
        End Select

    End Sub

    Private Sub DGV_Master_Sorted(ByVal sender As Object, ByVal e As System.EventArgs) Handles DGV_Master.Sorted

        If MasterDS.Tables(0).Rows.Count > 0 Then
            SetGridRowBackColor(Me.DGV_Master, MasterDS)
        End If
    End Sub

    Private Sub DGV_Sum_RowPostPaint(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowPostPaintEventArgs) Handles DGV_Sum.RowPostPaint
        e.Graphics.DrawString("合計:", Me.DGV_Sum.DefaultCellStyle.Font, Brushes.Black, e.RowBounds.Location.X + 8, e.RowBounds.Location.Y + 8)
    End Sub

    Private Sub RadioButton1_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles RadioButton1.CheckedChanged
        If Me.RadioButton1.Checked = True Then
            Me.Panel6.Visible = True
            Me.Panel2.Visible = False
        End If
    End Sub

    Private Sub RadioButton2_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles RadioButton2.CheckedChanged
        If Me.RadioButton2.Checked = True Then
            Me.Panel2.Visible = True
            Me.Panel6.Visible = False
        End If
        Me.cmbGoodsBarcode.Enabled = Me.RadioButton2.Checked
        Me.cmbBatch.Enabled = Me.RadioButton2.Checked
        Me.GoodsCount.Enabled = Me.RadioButton2.Checked
        If Me.RadioButton2.Checked = True Then
            Me.cmbGoodsBarcode.Focus()
        End If
    End Sub

    Private Sub txtGoodsBarcode_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtGoodsBarcode.KeyDown

        Dim WhereStr As String
        Dim sql As String
        Dim m_Ds As New DataSet
        Try
            Me.Laberror.Visible = False
            If Me.txtGoodsBarcode.Text.Length > 0 Then

                If e.KeyCode = Keys.Enter Then
                    If Me.cmbOutStoreType.SelectedIndex = 1 Then
                        'WhereStr = " and isnull(e.fVirtual,'')=1"
                    Else
                        WhereStr = " and isnull(e.fVirtual,'')<>1 and isnull(e.fBuJian,'')<>1"
                    End If
                    sql = "select a.Period,a.StoreHouse,replace(a.Barcode,'*','') as Barcode,a.Batch,a.StorePlace,a.Goodsamount,b.Code,b.SupperItem,b.Cnname,b.Enname,c.ColorSName as Color,d.SizeSName as Spec from "
                    sql += " (select Period,StoreHouse,BarCode,Batch,StorePlace,sum(Goodsamount) as Goodsamount from V_VisualStoreQuery   group by StoreHouse,Period,barcode,Batch,StorePlace) a"
                    sql += " inner join BSC_Goods b on a.BarCode=b.BarCode"
                    sql += " inner join BSC_ColorDefine c on b.Color=c.ColorCode "
                    sql += " inner join BSC_SizeDefine d on b.Spec=d.SizeCode "
                    sql += " left join BSC_Storage e on a.StorePlace=e.fStorageId"
                    sql += " where a.StoreHouse='" & PubCompanyCode & "' and isnull(a.Goodsamount,0.00)>0" & WhereStr & " and isnull(a.BarCode,'')='*" & Me.txtGoodsBarcode.Text & "*' order by substring(Batch,4,3),substring(Batch,1,3),Goodsamount"

                    m_Ds = ReturnDataset(sql)
                    If m_Ds.Tables(0).Rows.Count > 0 Then
                        For Each mRow As DataRow In m_Ds.Tables(0).Rows
                            Dim NewRow As DataRow = DetailDS.Tables(0).NewRow
                            Dim Rows() As DataRow = DetailDS.Tables(0).Select("GoodsBarCode='" & mRow("BarCode") & "' and Batch='" & mRow("batch") & "' and storeplace='" & mRow("storeplace") & "'")
                            If Rows.Length > 0 Then
                                Dim ItemNo As String = Rows(0).Item("GoodsBarCode") & ""
                                Dim RowIndex As Integer = 0
                                For j As Integer = 0 To DetailDS.Tables(0).Rows.Count - 1
                                    If DetailDS.Tables(0).Rows(j).Item("GoodsBarCode").ToString.ToLower = ItemNo.ToLower Then
                                        RowIndex = j
                                        Exit For
                                    End If
                                Next
                                If Me.cmbOutStoreType.SelectedIndex = 4 Then
                                    NewRow("ItemNo") = Format(DetailDS.Tables(0).Rows.Count + 1, "000")
                                    NewRow("GoodsBarCode") = mRow("BarCode") & ""
                                    NewRow("GoodsCode") = mRow("Code") & ""
                                    NewRow("SupperItem") = mRow("SupperItem") & ""
                                    NewRow("GoodsName") = mRow("Cnname") & ""
                                    NewRow("GoodsEname") = mRow("Enname") & ""
                                    NewRow("GoodsSpec") = mRow("Spec") & ""
                                    NewRow("goodsamount") = Format(1, "#0.00")
                                    NewRow("Batch") = mRow("batch") & ""
                                    NewRow("storeplace") = mRow("storeplace") & ""
                                    DetailDS.Tables(0).Rows.Add(NewRow)
                                Else
                                    DetailDS.Tables(0).Rows(RowIndex).Item("goodsamount") += Format(1, "#0.00")
                                    DetailDS.Tables(0).AcceptChanges()
                                    'MsgBox("貨品 [" & mRow("BarCode") & "] 已經存在列表中！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                                    'Me.DGV_Detail.Focus()
                                    'Me.DGV_Detail.CurrentCell = Me.DGV_Detail.Rows(RowIndex).Cells("goodsamount")
                                    'Exit Sub
                                End If
                            Else
                                NewRow("ItemNo") = Format(DetailDS.Tables(0).Rows.Count + 1, "000")
                                NewRow("GoodsBarCode") = mRow("BarCode") & ""
                                NewRow("GoodsCode") = mRow("Code") & ""
                                NewRow("SupperItem") = mRow("SupperItem") & ""
                                NewRow("GoodsName") = mRow("Cnname") & ""
                                NewRow("GoodsEname") = mRow("Enname") & ""
                                NewRow("GoodsSpec") = mRow("Spec") & ""
                                NewRow("goodsamount") = Format(1, "#0.00")
                                NewRow("Batch") = mRow("batch") & ""
                                NewRow("storeplace") = mRow("storeplace") & ""
                                DetailDS.Tables(0).Rows.Add(NewRow)
                            End If
                            Exit For
                        Next
                        DetailDS.AcceptChanges()
                        Me.DGV_Detail.DataSource = DetailDS.Tables(0)
                        Me.DGV_Detail.CurrentCell = Me.DGV_Detail.Rows(Me.DGV_Detail.Rows.Count - 2).Cells("Goodsamount")
                        Me.txtGoodsBarcode.Text = ""
                        Me.txtGoodsBarcode.Focus()
                    End If
                Else
                    Me.Laberror.Visible = True
                    Me.Laberror.Text = "條碼不能為空！"
                    Me.txtGoodsBarcode.Focus()
                End If

            End If
        Catch ex As Exception
            MsgBox("txtGoodsBarcode_TextChanged:" & ex.Message, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        Finally
            m_Ds = Nothing
        End Try

    End Sub

    Private Sub DGV_Detail_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles DGV_Detail.DoubleClick

        If ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp Then
            If Me.TabControl1.SelectedIndex <> 2 Then
                Me.TabControl1.SelectedIndex = 2
            End If
        End If

    End Sub

    Private Sub txtElementNo_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtElementNo.KeyDown

        Try
            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
                If e.KeyCode = Keys.Enter Then
                    CreateElement(Me.txtElementNo.Text)
                    Me.txtElementNo.Text = ""
                ElseIf e.KeyCode = Keys.Tab Then
                    Me.lstviewelement.Focus()
                    Me.lstviewelement.Items(0).Selected = True
                End If
            End If
        Catch ex As Exception
            MsgBox("txtElementNo_KeyDown:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub txtElementcount_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs)
        If e.KeyCode = Keys.Enter Then
            Me.txtElementNo.Focus()
        End If
    End Sub

    Private Sub txtElementcount_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)

    End Sub

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub dgv_Element_RowPostPaint(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowPostPaintEventArgs)
        Try
            e.Graphics.DrawString(e.RowIndex + 1, dgv_Element.DefaultCellStyle.Font, Brushes.Black, e.RowBounds.Location.X + 5, e.RowBounds.Location.Y + 4)
        Catch ex As Exception
            MsgBox("dgv_Element_RowPostPaint:", MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

#End Region

#Region "ExitToolStripMenuItem_Click"

    Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
        Exit Sub
    End Sub

    Private Sub ImportDSCIAToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Try
            IsImport = True
            Dim Qty As Integer = 0
            Dim Pathstr As String = String.Empty
            With Me.OpenFileDialog1
                .FileName = "IA.xml"
                .Filter = "*.xml|*.xml"
            End With

            If Me.OpenFileDialog1.ShowDialog = DialogResult.OK Then
                Pathstr = Me.OpenFileDialog1.FileName
            Else
                Exit Sub
            End If

            Dim XmlDoc As XmlDocument = New XmlDocument
            Dim Node As XmlNode
            Dim Subnode As XmlNode
            XmlDoc.Load(Pathstr)
            Node = XmlDoc.SelectSingleNode("*")
            Subnode = Nothing
            GetXmlNode(Node, Subnode)


            If Not Subnode Is Nothing Then

                dt = New DataTable("Reprot")
                dt.Columns.Add("SEQ_NO", GetType(System.Int32))
                dt.Columns.Add("ITEM_NO", GetType(System.String))
                dt.Columns.Add("WHFROM", GetType(System.String))
                dt.Columns.Add("WHFROM_D", GetType(System.String))
                dt.Columns.Add("WHTO_D", GetType(System.String))
                dt.Columns.Add("WHTO", GetType(System.String))
                dt.Columns.Add("FTY_NO", GetType(System.String))
                dt.Columns.Add("DESCRIPT", GetType(System.String))
                dt.Columns.Add("REM_LINE", GetType(System.String))
                dt.Columns.Add("QTY", GetType(System.Decimal))
                dt.AcceptChanges()


                For Each node2 As XmlNode In Subnode.ChildNodes
                    Dim row As DataRow = dt.NewRow
                    For Each a As XmlAttribute In node2.Attributes
                        If dt.Columns.Contains(a.Name) Then
                            row(a.Name) = a.Value
                        End If
                    Next
                    dt.Rows.Add(row)
                    dt.AcceptChanges()
                Next
                Dim fbarcode As System.Text.StringBuilder = New System.Text.StringBuilder
                Dim Sql As String = String.Empty
                If dt.Rows.Count > 0 Then
                    For Each gRow As DataRow In dt.Rows
                        If fbarcode.ToString.Length > 0 Then
                            fbarcode.Append(",")
                        End If
                        fbarcode.Append("'")
                        fbarcode.Append(gRow("ITEM_NO"))
                        fbarcode.Append("'")
                    Next
                    Sql = "select replace(barcode,'*','') as BarCode,enname from bsc_goods  where enname in (" & fbarcode.ToString & ")"
                    Dim Rst As DataSet = New DataSet
                    Rst = ReturnDataset(Sql)

                    Dim NewTable As DataTable = Rst.Tables(0).Copy
                    Dim barcode As System.Text.StringBuilder = New System.Text.StringBuilder
                    If NewTable.Rows.Count > 0 Then
                        For Each frow As DataRow In NewTable.Rows
                            'barcode.Append(frow("BarCode"))
                            Dim enname As String = frow("enname")
                            Dim Rows2() As DataRow = dt.Select("item_No='" & enname & "'")
                            If Rows2.Length > 0 Then
                                For Each Enrow As DataRow In Rows2
                                    'Dim currentbatch As String = String.Empty
                                    'Dim Storeplace As String = String.Empty
                                    Qty = Enrow("qty")
                                    ImportAddDataToGrid2(frow("barcode"), Qty)
                                    AutoAddNewRow(frow("barcode"), currentBatch, currentStoreplace, Qty)

                                Next
                            End If
                        Next
                    End If

                End If
            End If
        Catch ex As Exception
            MsgBox("ImportDSCIAToolStripMenuItem_Click:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub GetXmlNode(ByVal ParentNode As XmlNode, ByRef NewNode As XmlNode)
        Try
            If ParentNode Is Nothing Then
                Exit Sub
            End If
            If ParentNode.Name.ToString = "Detail_Collection" Then
                NewNode = ParentNode
                Exit Sub
            End If
            For Each Tempnode As XmlNode In ParentNode.ChildNodes
                If Tempnode.Name.ToString = "Detail_Collection" Then
                    NewNode = Tempnode
                    Exit Sub
                End If
                If Tempnode.Name.ToString = "listIA_Details_Group" Then
                    For Each sonnode As XmlNode In Tempnode.ChildNodes
                        ParentNode = sonnode
                        For Each Tempnode2 As XmlNode In ParentNode.ChildNodes
                            If Tempnode.Name.ToString = "Detail_Collection" Then
                                NewNode = Tempnode
                                Exit Sub
                            End If
                            If Not Tempnode2.Name.ToString Is Nothing Then
                                GetXmlNode(Tempnode, NewNode)
                            End If
                        Next
                    Next
                End If
                If Not Tempnode.Name.ToString Is Nothing Then
                    GetXmlNode(Tempnode, NewNode)
                End If
            Next
        Catch ex As Exception
            MsgBox("GetXmlNode:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub IAToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles IAToolStripMenuItem.Click
        Try


            Dim Qty As Integer = 0
            Dim IANum As String
            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then

                If Me.cmbOutStoreType.SelectedIndex <> 2 Then
                    MessageBox.Show("請選擇調撥出庫", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information)
                    Me.cmbOutStoreType.Focus()
                    Me.cmbOutStoreType.SelectedIndex = 2
                    Exit Sub
                End If

                Dim sql As String = String.Empty
                Dim SelectIA As New Frm_SelectIA
                Dim DT As DataTable
                SelectIA.ShowDialog()
                If SelectIA.DataGridView1.Rows.Count > 0 Then
                    DT = CType(SelectIA.DataGridView1.DataSource, DataTable)
                Else
                    Exit Sub
                End If



                Dim fbarcode As System.Text.StringBuilder = New System.Text.StringBuilder
                Dim WHTO As System.Text.StringBuilder = New System.Text.StringBuilder

                For Each gRow As DataRow In DT.Rows
                    If fbarcode.ToString.Length > 0 Then
                        fbarcode.Append(",")
                    End If
                    fbarcode.Append("'")
                    fbarcode.Append(gRow("ITEM_NO"))
                    fbarcode.Append("'")
                Next
                '找出目的倉庫
                For Each TORow As DataRow In DT.Rows
                    If WHTO.ToString.Length > 0 Then
                        WHTO.Append(",")
                    End If
                    WHTO.Append("'")
                    WHTO.Append(TORow("WHTO"))
                    WHTO.Append("'")
                Next

                sql = "select distinct  ListB  from BSC_OtherDefineB where ItemNo= '77' and ListB in (" & WHTO.ToString & ") "
                'sql += " select * from dbo.Sal_IAA where VOUCHER_NO in(" & IANum.ToString & ")"
                'Me.txtRemark.Text = IANum.ToString
                Dim DS As DataSet = New DataSet
                DS = ReturnDataset(sql)
                If DS.Tables(0).Rows.Count = 1 Then
                    Me.cmbToStore1.SelectedValue = DS.Tables(0).Rows(0)(0)
                ElseIf DS.Tables(0).Rows.Count > 1 Then
                    MessageBox.Show("送達的目的倉不唯一", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information)
                    Exit Sub
                Else
                    MessageBox.Show("送達的目的倉為空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information)
                    Exit Sub
                End If

                sql = "select replace(barcode,'*','') as BarCode,enname from bsc_goods  where enname in (" & fbarcode.ToString & ")"
                Dim Rst As DataSet = New DataSet
                Rst = ReturnDataset(sql)

                Dim NewTable As DataTable = Rst.Tables(0).Copy
                Dim barcode As System.Text.StringBuilder = New System.Text.StringBuilder
                If NewTable.Rows.Count > 0 Then
                    For Each frow As DataRow In NewTable.Rows
                        'barcode.Append(frow("BarCode"))

                        Dim enname As String = frow("enname")
                        Dim Rows2() As DataRow = DT.Select("item_No='" & enname & "'")
                        If Rows2.Length > 0 Then
                            For Each Enrow As DataRow In Rows2
                                'Dim currentbatch As String = String.Empty
                                'Dim Storeplace As String = String.Empty
                                IANum = Enrow("VOUCHER_NO")
                                Qty = Enrow("qty")
                                ImportAddDataToGridIA(frow("barcode"), Qty, IANum)
                                AutoAddNewRowIA(frow("barcode"), currentBatch, currentStoreplace, Qty, IANum)
                            Next
                        End If
                    Next
                End If

            End If

        Catch ex As Exception

        End Try
    End Sub
#End Region

    Private Sub DGV_Master_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles DGV_Master.Paint
        FormatDgrd(DGV_Master, "BoStatus")
    End Sub

    Private Sub DNToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DNToolStripMenuItem.Click

        If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then



            If Me.cmbOutStoreType.SelectedIndex <> 4 Then
                MessageBox.Show("請選擇配送出庫", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information)
                Me.cmbOutStoreType.Focus()
                Me.cmbOutStoreType.SelectedIndex = 4
                Exit Sub
            End If
            Try
                ActionImport()
            Catch ex As Exception

            End Try

        End If
    End Sub

    Private Sub SaleOrdeToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaleOrdeToolStripMenuItem.Click


        Try


            Dim Qty As Integer = 0
            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
                If Me.cmbOutStoreType.SelectedIndex <> 5 Then
                    MessageBox.Show("請選擇銷售出庫", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information)
                    Me.cmbOutStoreType.Focus()
                    Me.cmbOutStoreType.SelectedIndex = 5
                    Exit Sub
                End If

                Dim sql As String = String.Empty
                Dim SelectSalePact As New Frm_SelectSalePact
                Dim DT As DataTable
                If SelectSalePact.ShowDialog() = DialogResult.OK Then
                    If SelectSalePact.DataGridView1.Rows.Count > 0 Then
                        DT = CType(SelectSalePact.DataGridView1.DataSource, DataTable)
                    Else
                        Exit Sub
                    End If
                Else
                    Exit Sub
                End If

                ' Dim fbarcode As System.Text.StringBuilder = New System.Text.StringBuilder
                ' Dim WHTO As System.Text.StringBuilder = New System.Text.StringBuilder
                If DT.Rows.Count > 0 Then

                    For Each frow As DataRow In DT.Rows
                        Dim enname As String = frow("enname")
                        Dim Rows2() As DataRow = DT.Select("enname='" & enname & "'")
                        If Rows2.Length > 0 Then
                            For Each Enrow As DataRow In Rows2
                                Qty = Enrow("fTotal")
                                If Qty > 0 Then
                                    ImportAddDataToGrid2(frow("fGoodsBarCode"), Qty)
                                    AutoAddNewRow(frow("fGoodsBarCode"), currentBatch, currentStoreplace, Qty)
                                End If

                            Next
                        End If
                    Next


                End If
            End If
        Catch ex As Exception

        End Try

    End Sub

    Private Sub MauToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MauToolStripMenuItem.Click
        If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then


            If Me.cmbOutStoreType.SelectedIndex <> 7 Then
                MessageBox.Show("請選擇半成品出庫", "加朗軟體", MessageBoxButtons.OK, MessageBoxIcon.Information)
                Me.cmbOutStoreType.Focus()
                Me.cmbOutStoreType.SelectedIndex = 7
                Exit Sub
            End If


            Dim SelectMau As New Frm_SelectMau
            Dim DT As DataTable

            If SelectMau.ShowDialog() = DialogResult.OK Then
                If SelectMau.DataGridView1.Rows.Count > 0 Then
                    DT = CType(SelectMau.DataGridView1.DataSource, DataTable)
                Else
                    Exit Sub
                End If
            Else
                Exit Sub
            End If

            Dim DATable As New DataTable

            '篩選出選擇的記錄
            Dim ISSELECTEDRows() As DataRow = DT.Select("ISSELECTED= TRUE")
            For i As Int32 = 0 To ISSELECTEDRows.Length - 1
                Dim GoodBarCode As String = ISSELECTEDRows(i)("Barcode").ToString()
                Dim QTY As Int32 = CType(ISSELECTEDRows(i)("qty").ToString(), Int32)
                ImportAddDataToGrid2(GoodBarCode, QTY)
                AutoAddNewRow(GoodBarCode, currentBatch, currentStoreplace, QTY)
            Next

        End If
    End Sub

    Private Sub DGV_Detail_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DGV_Detail.Leave

    End Sub

    Private Sub DGV_Master_RowPostPaint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewRowPostPaintEventArgs) Handles DGV_Master.RowPostPaint, DGV_Detail.RowPostPaint, dgv_Element.RowPostPaint
        Try
            Dim DGView As DataGridView = DirectCast(sender, DataGridView)
            Dim SBrush As New SolidBrush(DGView.RowHeadersDefaultCellStyle.ForeColor)
            e.Graphics.DrawString(Convert.ToString(e.RowIndex + 1, System.Globalization.CultureInfo.CurrentCulture), e.InheritedRowStyle.Font, SBrush, e.RowBounds.Location.X + 20, e.RowBounds.Location.Y + 4)
        Catch ex As Exception
            MessageBox.Show("DGV_RowPostPaint:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub txtRemark_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtRemark.TextChanged

    End Sub

    Private Sub txtEleBarcode_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtEleBarcode.TextChanged

    End Sub

    Private Sub DGV_Detail_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DGV_Detail.CellContentClick

    End Sub
End Class

